๐ ์๊ณ ๋ฆฌ์ฆ ์ ๋ฆฌ
๐ ๋ฌธ์
https://www.acmicpc.net/problem/13549
13549๋ฒ: ์จ๋ฐ๊ผญ์ง 3
์๋น์ด๋ ๋์๊ณผ ์จ๋ฐ๊ผญ์ง์ ํ๊ณ ์๋ค. ์๋น์ด๋ ํ์ฌ ์ N(0 ≤ N ≤ 100,000)์ ์๊ณ , ๋์์ ์ K(0 ≤ K ≤ 100,000)์ ์๋ค. ์๋น์ด๋ ๊ฑท๊ฑฐ๋ ์๊ฐ์ด๋์ ํ ์ ์๋ค. ๋ง์ฝ, ์๋น์ด์ ์์น๊ฐ X์ผ
www.acmicpc.net
โ ํ์ด๊ณผ์
import sys
from collections import deque
MAX = 100001
n, k = map(int, input().split())
queue = deque([n])
dist = [-1]*MAX
dist[n] = 0
while queue:
i = queue.popleft()
if i == k:
print(dist[i])
break
if i*2 < MAX and dist[i*2] == -1:
queue.appendleft(i*2)
dist[i*2] = dist[i]
if i-1>=0 and dist[i-1] == -1:
queue.append(i-1)
dist[i-1] = dist[i] + 1
if i+1< MAX and dist[i+1] == -1:
queue.append(i + 1)
dist[i+1] = dist[i] + 1
์๋ ์ ํ์ด๋ณธ ๋ฌธ์ ์๊ณ bfs๋ก ํ์๋ค.
(๋ฌธ์ A->B)์์๋ +"1"๊ณผ *2๋ฐ์ ์์ด์ ๋ค๋ก ๋์์ค์ง ๋ชปํ๋ ๋ฐ๋ฉด์
์ด ๋ฌธ์ ๋ -1๋ ์๊ธฐ ๋๋ฌธ์ dist๋ฅผ ๋์ด ํด๋น ์์น์ ๋ฐฉ๋ฌธํ๋์ง๋ฅผ ํ์ธํด์ผ ํ๋ค.
* (3 -> 4 -> 3) ๊ฐ์ ๊ฒฝ์ฐ๋ฅผ ๋ฐฉ์งํ๊ธฐ ์ํด์
(*2)๋ฅผ ํ๋ ๊ฒฝ์ฐ์๋ ์ด๊ฐ ์ฆ๊ฐํ์ง ์์ผ๋ฏ๋ก appendleft๋ฅผ ํด์ฃผ์๋ค.