ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

์ˆจ๋ฐ”๊ผญ์งˆ ์‹œ๋ฆฌ์ฆˆ

 

๋ฌธ์ œ

 

13549๋ฒˆ: ์ˆจ๋ฐ”๊ผญ์งˆ 3

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

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

 ๊ธฐ๋ณธ์ ์ธ ํ’€์ด ๋ฐฉ์‹์€ 1697 ์ˆจ๋ฐ”๊ผญ์งˆ๊ณผ ๊ฐ™๋‹ค. ํ•˜์ง€๋งŒ ์ˆœ๊ฐ„์ด๋™ ํ•  ๊ฒฝ์šฐ, 0์ดˆ์˜ ์‹œ๊ฐ„์ด ๊ฑธ๋ฆฌ๋ฏ€๋กœ ์ˆœ๊ฐ„์ด๋™ ํ•˜๋Š” ๊ฒฝ์šฐ์— ์šฐ์„ ์ˆœ์œ„๋ฅผ ๋‘์–ด ์ฒ˜๋ฆฌํ•˜์—ฌ์•ผ ํ•œ๋‹ค. ์ฆ‰, ๊ฐ€์ค‘์น˜๋ฅผ ๊ฐ€์ง€๋Š” ๊ทธ๋ž˜ํ”„๊ฐ€ ๋œ๋‹ค๋Š” ๊ฒƒ๊ณผ ๊ฐ™๋‹ค. ๋งŒ์•ฝ ํ˜„์žฌ ์œ„์น˜ - 1, ํ˜„์žฌ ์œ„์น˜ + 1, ํ˜„์žฌ ์œ„์น˜ * 2์˜ ์šฐ์„  ์ˆœ์œ„๊ฐ€ ๊ฐ๊ฐ ๋‹ค๋ฅด๋‹ค๋ฉด ๋‹ค์ต์ŠคํŠธ๋ผ๋กœ ํ’€์–ด์•ผ ํ•œ๋‹ค. ํ•˜์ง€๋งŒ ๋ฌธ์ œ์—์„œ๋Š” ํ˜„์žฌ ์œ„์น˜ * 2(์ˆœ๊ฐ„ ์ด๋™)์ธ ๊ฒฝ์šฐ๋งŒ ์šฐ์„ ์ ์œผ๋กœ ์ฒ˜๋ฆฌํ•˜๋ฉด ๋˜๊ธฐ์— BFS๋กœ ํ’€ ์ˆ˜ ์žˆ๋‹ค.

 

์ฝ”๋“œ

from sys import stdin
from collections import deque


def bfs(start):
    q = deque([start])

    while q:
        cur_loc = q.popleft()
        if cur_loc == k:
            return visited[cur_loc]

        for next_loc in (cur_loc - 1, cur_loc + 1, cur_loc * 2):
            if 0 <= next_loc < MAX_LOC and not visited[next_loc]:
                visited[next_loc] = visited[cur_loc]

                if next_loc == cur_loc * 2 and cur_loc > 0:
                    q.appendleft(next_loc)
                else:
                    visited[next_loc] = visited[cur_loc] + 1
                    q.append(next_loc)


if __name__ == '__main__':
    MAX_LOC = 100001
    n, k = map(int, stdin.readline().split())
    visited = [0] * MAX_LOC
    print(bfs(n))

 ์ˆœ๊ฐ„์ด๋™ (ํ˜„์žฌ์œ„์น˜ * 2)์— ์šฐ์„ ์ˆœ์œ„๋ฅผ ๋‘๊ธฐ ์œ„ํ•ด, ๊ณฑํ•˜๊ธฐ ์ธ ๊ฒฝ์šฐ ํ์˜ ์ขŒ์ธก์— ์‚ฝ์ž…ํ•˜์—ฌ ๋จผ์ € ์ฒ˜๋ฆฌ ๋  ์ˆ˜ ์žˆ๋„๋ก ํ•˜์˜€๋‹ค.

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€