ํ์ด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';
}