ํ’€์ด1

์‹ค๋ฒ„1 : BFS ๋ฌธ์ œ์ด๋‹ค.

Code

from collections import deque
import sys
 
 
input = sys.stdin.readline
 
MAXNUM = 1e6
N, K = map(int, input().split())
visited = [False] * int(MAXNUM + 1)
 
 
def BFS():
    q = deque()
    q.append((N, 0))  # position, cost
 
    while q:
        pos, cost = q.popleft()
        visited[pos] = True
 
        if pos == K:
            return cost
 
        nexts = [(pos - 1, cost + 1), (pos + 1, cost + 1), (2 * pos, cost + 1)]
 
        for npos, ncost in nexts:
            if 0 <= npos <= MAXNUM and visited[npos] == False:
                q.append((npos, ncost))
 
 
ans = BFS()
print(ans)
 

ํ’€์ด2

์‹ค๋ฒ„2 : ๊ทธ๋ž˜ํ”„ ๋ฌธ์ œ์ด๋‹ค.

์ด ๋ฌธ์ œ์˜ ํ•ต์‹ฌ์€, ํ•ด๋‹น ์œ„์น˜์—์„œ 3๊ฐ€์ง€์˜ ์„ ํƒ์„ ํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ์ ์ด๋‹ค. ์ด 3๊ฐ€์ง€์˜ ์„ ํƒ ๊ฐ๊ฐ์— ํ•ด๋‹นํ•˜๋Š” ์œ„์น˜์—์„œ ๋˜ 3๊ฐ€์ง€์˜ ์„ ํƒ์„ ํ•  ์ˆ˜ ์žˆ๋‹ค. ๊ทธ ์„ ํƒ์„ ์—ฐ์ด์–ดํ•œ ๊ฒฐ๊ณผ ๋ฌธ์ œ์˜ ๋‹ต์ด ์žˆ๋‹ค.

ํ•˜์ง€๋งŒ ์ด ๋ฌธ์ œ๋Š” DFS๋กœ ์ ‘๊ทผํ•  ์ˆ˜ ์—†๋Š”๋ฐ, ๊ทธ ์ด์œ ๋Š”, ๊ฐ๊ฐ์˜ ์„ ํƒ์„ ๊นŠ์ด ๊ธฐ์ค€์œผ๋กœ ํƒ์ƒ‰ํ–ˆ์„ ๋•Œ, ๋‹ต์— ๋‹ค๋‹ค๋ฅด์ง€ ๋ชปํ•˜๋Š” ์ƒํ™ฉ์ด ์žˆ์„ ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ๋”ฐ๋ผ์„œ ๋ฌดํ•œ ๋ฃจํ”„์— ๋น ์ง€๊ฑฐ๋‚˜, ํ˜น์€ ์ด ๋ถ€๋ถ„์„ ๊ฑฐ๋ฅด๋Š” ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•ด์•ผ ํ•˜๋Š”๋ฐ ์ƒ๋‹นํžˆ ๋ฒˆ๊ฑฐ๋กญ๋‹ค.

์ด๋Ÿฐ ๊ฒฝ์šฐ ์˜คํžˆ๋ ค BFS๋กœ ์ƒ๊ฐํ–ˆ์„ ๋•Œ, ๋ฌธ์ œ๊ฐ€ ํ™• ์™€๋‹ฟ๋Š” ๊ฒฝ์šฐ๊ฐ€ ๋งŽ๋‹ค. BFS๋กœ ํƒ์ƒ‰ํ•  ๊ฒฝ์šฐ, ์‹œ๊ฐ„์˜ ๊ธฐ์ค€์œผ๋กœ ์™„์ „ ํƒ์ƒ‰ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ด ๋ฌธ์ œ์˜ ์˜๋„์™€ ์ •ํ™•ํžˆ ๋งž์•„ ๋–จ์–ด์ง„๋‹ค. ์ตœ๋Œ€ํ•œ ์งง์€ ์‹œ๊ฐ„์— ๋‹ต๊ณผ ์ผ์น˜ํ•  ๊ฒฝ์šฐ ๋ฐ˜๋ณต๋ฌธ์„ ๋น ์ ธ๋‚˜์˜ค๋ฉด ๋˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ๋”ฐ๋ผ์„œ ์œ„์น˜์— ๋”ฐ๋ฅธ ์‹œ๊ฐ„์„ ์ €์žฅํ•  ํ•„์š”๊ฐ€ ์žˆ๋‹ค.

์ด ๋•Œ, ์„ ํƒ์ง€์— ์ด ์žˆ๊ณ  ์ค‘๊ฐ„์ค‘๊ฐ„ ๋„ ์žˆ์–ด ์ค‘๋ณต๋˜๋Š” ์œ„์น˜์— ๋ฐฉ๋ฌธํ•  ๊ฐ€๋Šฅ์„ฑ์ด ์žˆ๋‹ค. ์ด ๋ถ€๋ถ„์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ์ค„์ด๊ธฐ ์œ„ํ•ด ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ฝ”๋“œ๋ฅผ ์งฐ๋‹ค.

Code

// ์‹ค๋ฒ„1 : ๋ฐฑ์ค€ 1697๋ฒˆ ์ˆจ๋ฐ”๊ผญ์งˆ
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
int N = 0, K = 0;
bool map[100001] = {0};
 
int main(){
    cin >> N >> K;
    queue<pair<int, int>> q;
    int ans = 0;
    q.push(make_pair(N, 0));
 
    while (!q.empty()) {
        int now = q.front().first, time = q.front().second;
        q.pop();
        if (map[now] == true) continue;
        map[now] = true;
 
        if (now == K) {
            ans = time; break;
        }
 
        if (now-1 >= 0) q.push(make_pair(now-1, time+1));
        if (now+1 <= 100000) q.push(make_pair(now+1, time+1));
        if (now*2 <= 100000) q.push(make_pair(now*2, time+1));
    }
    cout << ans << '\n';
}

Reference