Post

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

๐Ÿ“Œ๋ฌธ์ œ

Alt text

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

  1. ์ตœ์†Œํž™์„ ์‚ฌ์šฉํ•œ bfs
    ์‹œ๊ฐ„์„ ๋…ธ๋“œ๋กœ ์ตœ์†Œํž™์„ queue๋กœ ์‚ฌ์šฉํ•˜๋ฉด ๊ฐ€์žฅ ์ ๊ฒŒ ๊ฑธ๋ฆฐ ์‹œ๊ฐ„์ด ๋จผ์ € ๋‚˜์˜จ๋‹ค.
    ์ด ๋ฌธ์ œ๋Š” ์–ด๋–ป๊ฒŒ ์›€์ง์ด๋“ (x+1, x-1, 2*x) time+1์ด๊ธฐ๋•Œ๋ฌธ์— ๊ตณ์ด ์ตœ์†Œํž™์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  deque๋ฅผ ์‚ฌ์šฉํ•ด๋„ ๋œ๋‹ค.

  2. ๊ฐ€์žฅ ์ ๊ฒŒ ๊ฑธ๋ฆฐ ์‹œ๊ฐ„ ๊ตฌํ•˜๊ธฐ
    pop๋œ ํ˜„์žฌ ์œ„์น˜๊ฐ€ ๋™์ƒ์˜ ์œ„์น˜(K)๋ผ๋ฉด ๊ฐ€์žฅ ์ ๊ฒŒ ๊ฑธ๋ฆฐ ์‹œ๊ฐ„์ด๋‹ค.

  3. ๊ฐ€์žฅ ์ ๊ฒŒ ๊ฑธ๋ฆฐ ์‹œ๊ฐ„์— ๋ฐฉ๋ฌธ ํšŸ์ˆ˜ ๊ตฌํ•˜๊ธฐ
    ๋จผ์ € ๊ฐ€์žฅ ์ ๊ฒŒ ๊ฑธ๋ฆฐ ์‹œ๊ฐ„์„ ๊ตฌํ–ˆ๋Š”์ง€๋ฅผ ์ฒดํฌํ•œ๋‹ค.
    ์ด์ „์— ์‹œ๊ฐ„์„ ๊ตฌํ–ˆ๊ณ  ํ˜„์žฌ ์‹œ๊ฐ„์ด ๊ทธ ์‹œ๊ฐ„๋ณด๋‹ค ํฌ๋‹ค๋ฉด ํ™•์ธํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค.
    ์ตœ์†Œํž™์œผ๋กœ ๊ตฌ์„ฑ๋˜์—ˆ๊ธฐ ๋•Œ๋ฌธ์— ํ˜„์žฌ์‹œ๊ฐ„์ด ์ตœ์†Œ์‹œ๊ฐ„๋ณด๋‹ค ์ž‘์„ ์ˆ˜๋Š” ์—†๋‹ค.
    ํ˜„์žฌ ์‹œ๊ฐ„๊ณผ ์ตœ์†Œ์‹œ๊ฐ„์ด ๊ฐ™๊ณ  ํ˜„์žฌ์œ„์น˜๊ฐ€ ๋™์ƒ์˜ ์œ„์น˜๋ผ๋ฉด ๋ฐฉ๋ฌธ ํšŸ์ˆ˜๋ฅผ ++ํ•ด์ค€๋‹ค.

  4. ๋ฐฉ๋ฌธ์ฒดํฌ
    visited๋ฅผ ํ†ตํ•ด์„œ ๋ฐฉ๋ฌธํ•  ์œ„์น˜๋ฅผ ์ฒดํฌํ•˜์˜€๋‹ค. ๋ฒ”์œ„๊ฐ€ 0์—์„œ 100000๊นŒ์ง€์ด๊ธฐ ๋•Œ๋ฌธ์— ํ•ด๋‹น ์œ„์น˜์˜ ๋ฐฉ๋ฌธ์—ฌ๋ถ€์™€ ๋ฒ”์œ„์ฒดํฌ๋ฅผ ํ•ด์ค€๋‹ค.
    ๋™์ƒ์˜ ์œ„์น˜๋Š” ์ด์ „์— ๋ฐฉ๋ฌธํ–ˆ์–ด๋„ ๋ฐฉ๋ฌธํšŸ์ˆ˜๋ฅผ ๊ตฌํ•ด์•ผํ•˜๊ธฐ ๋•Œ๋ฌธ์— visited[K] ์ƒํƒœ๋ฅผ ๋ณ€๊ฒฝ์‹œํ‚ค์ง€ ์•Š๋Š”๋‹ค. ์ด๋ฅผ ์ œ์™ธํ•˜๋ฉด ์ผ๋ฐ˜์ ์ธ bfs๋ฌธ์ œ์™€ ๊ฐ™๋‹ค.

๐Ÿฅ‚์ฝ”๋“œ

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

N, K = map(int, input().split())
answer = -1
cnt = 0

def bfs():
    global answer, cnt
    queue = []
    visited = [False] * (100001)
    queue.append((0, N))
    visited[N] = True

    while queue:
        time, cur = heappop(queue)
        if answer != -1 and time > answer:
            return
        if cur == K:
            answer = time
            cnt += 1
            continue
        visited[cur] = True
        for nxt in [cur + 1, cur - 1, 2 * cur]:
            if 0 <= nxt < 100001 and not visited[nxt]:
                heappush(queue, (time + 1, nxt))

bfs()
print(answer)
print(cnt)
This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.