Post

[BOJ] 13549. ์ˆจ๋ฐ”๊ผญ์งˆ3(python)

๐Ÿ“Œ๋ฌธ์ œ

Alt text

๐Ÿ’ช์•„์ด๋””์–ด

  1. ํ•ด๋‹น ์œ„์น˜์—์„œ ์›€์ง์ด๊ธฐ
    ์›€์ง์ด๋Š” ๋ฐฉ๋ฒ•์€ ์•ž์œผ๋กœ ๊ฑท๊ธฐ(x+1), ๋’ค๋กœ ๊ฑท๊ธฐ(x-1), ์ˆœ๊ฐ„์ด๋™ํ•˜๊ธฐ(2*x)๋กœ, ์„ธ ๊ฐ€์ง€์ด๋‹ค.

  2. ์›€์ง์ด๋Š” ๋ฐฉ๋ฒ•๋ณ„ ์†Œ๋ชจ ์‹œ๊ฐ„
    ๊ฑธ์„ ๊ฒฝ์šฐ +1, ์ˆœ๊ฐ„์ด๋™ํ•  ๊ฒฝ์šฐ 0์˜ ์‹œ๊ฐ„์ด ์†Œ๋ชจ๋œ๋‹ค.
    ์ตœ์†Œ์˜ ์†Œ๋ชจ์‹œ๊ฐ„์„ ๊ตฌํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” ์†Œ๋ชจ์‹œ๊ฐ„์ด ์ ๊ฒŒ ๊ฑธ๋ฆฌ๋Š” ์›€์ง์ด๋Š” ๋ฐฉ๋ฒ•์„ ์„ ํƒํ•ด์•ผํ•˜๊ธฐ ๋•Œ๋ฌธ์— min heap์„ ์‚ฌ์šฉํ•œ๋‹ค.

  3. ์ตœ์†Œ์˜ ์‹œ๊ฐ„์œผ๋กœ ์›€์ง์ด๋Š” ๋ฐฉ๋ฒ•์ฐพ๊ธฐ
    bfs๋ฅผ ์‚ฌ์šฉํ•˜๋Š”๋ฐ min heap์„ ์‚ฌ์šฉํ•˜์—ฌ ์ตœ์†Œ์˜ ์‹œ๊ฐ„์ด ๊ฑธ๋ฆฌ๋Š” ๋ฐฉ๋ฒ•๋ถ€ํ„ฐ ํƒ์ƒ‰ํ•œ๋‹ค.
    (์‹œ๊ฐ„, ํ˜„์žฌ์œ„์น˜)๋กœ ์š”์†Œ๋ฅผ ๋„ฃ๋Š”๋‹ค. hepapop ์„ ํ•˜๋ฉด ํ˜„์žฌ์œ„์น˜์—์„œ ์ตœ์†Œ์˜ ์‹œ๊ฐ„์ด ๊ฑธ๋ฆฌ๋Š” ์š”์†Œ๊ฐ€ ๋‚˜์˜ฌ ๊ฒƒ์ด๊ธฐ ๋–„๋ฌธ์— ํ˜„์žฌ์œ„์น˜๊ฐ€ ๋™์ƒ์œ„์น˜์™€ ๊ฐ™์œผ๋ฉด ํƒ์ƒ‰์„ ์ข…๋ฃŒํ•œ๋‹ค.

๐Ÿฅ‚์ฝ”๋“œ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import sys; input = sys.stdin.readline
from heapq import heappush,heappop

def bfs():
    move[n] = 0
    heap = []
    heappush(heap,(0, n))

    while heap:
        cnt, cur = heappop(heap)
        if cur == k: 
            print(cnt)
            return
        for opt, c in [(cur+1,1), (cur-1,1), (2*cur,0)]:
            if 0 <= opt <= 100000:
                clock = cnt + c
                if move[opt] > clock:
                    move[opt] = clock
                    heappush(heap,(clock,opt))

n, k = map(int,input().split())
move = [float('inf')] * 100001
bfs()
This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.