DevYoon

[๋ฐฑ์ค€] 13913. ์ˆจ๋ฐ”๊ผญ์งˆ4 (Python) ๋ณธ๋ฌธ

PS/Baekjoon

[๋ฐฑ์ค€] 13913. ์ˆจ๋ฐ”๊ผญ์งˆ4 (Python)

gimewn 2022. 5. 17. 15:40

link ๐Ÿ”— https://www.acmicpc.net/problem/13913

 

13913๋ฒˆ: ์ˆจ๋ฐ”๊ผญ์งˆ 4

์ˆ˜๋นˆ์ด๋Š” ๋™์ƒ๊ณผ ์ˆจ๋ฐ”๊ผญ์งˆ์„ ํ•˜๊ณ  ์žˆ๋‹ค. ์ˆ˜๋นˆ์ด๋Š” ํ˜„์žฌ ์  N(0 ≤ N ≤ 100,000)์— ์žˆ๊ณ , ๋™์ƒ์€ ์  K(0 ≤ K ≤ 100,000)์— ์žˆ๋‹ค. ์ˆ˜๋นˆ์ด๋Š” ๊ฑท๊ฑฐ๋‚˜ ์ˆœ๊ฐ„์ด๋™์„ ํ•  ์ˆ˜ ์žˆ๋‹ค. ๋งŒ์•ฝ, ์ˆ˜๋นˆ์ด์˜ ์œ„์น˜๊ฐ€ X์ผ

www.acmicpc.net

 

๐Ÿ’ซ ๊ฐ€์žฅ ๋นจ๋ฆฌ ๋™์ƒ์„ ์ฐพ๋Š” ์‹œ๊ฐ„๊ณผ ๊ทธ ๋ฃจํŠธ๋ฅผ ์ถœ๋ ฅํ•ด์ฃผ์–ด์•ผ ํ•œ๋‹ค.

๐Ÿ’ซ check ๋ฐฐ์—ด์˜ ์•ž์œผ๋กœ ๋“ค์–ด๊ฐˆ ๊ฐ’์˜ ์œ„์น˜์— ํ˜„์žฌ ์œ„์น˜๋ฅผ ์ ์–ด์ฃผ์—ˆ๊ณ , ์—ญ์ถ”์ ํ•ด์ฃผ์—ˆ๋‹ค.

 

from collections import deque

def BFS(start, target):
    q = deque()
    q.append((start, 0)) # start, cnt
    Mincnt = 0
    Minpath = []
    check = [-1]*100001
    while q:
        now, cnt = q.popleft()
        if now == target:
            Mincnt = cnt
            break

        path = [now-1, now+1, now*2]

        for p in path:
            if 0<= p <= 100000 and check[p] == -1:
                check[p] = now # check[์•ž์œผ๋กœ ๊ฐˆ ์œ„์น˜]์— ํ˜„์žฌ ์œ„์น˜ ๋„ฃ์–ด์ฃผ๊ธฐ
                q.append((p, cnt+1))

    now = target
    for _ in range(Mincnt+1): # ๋ฃจํŠธ ์—ญ์œผ๋กœ ์ถ”์ฒ™
        Minpath.append(now)
        now = check[now]

    return Mincnt, Minpath[::-1]

n, k = map(int, input().split())

res = BFS(n, k)

print(res[0])
print(*res[1])