https://www.acmicpc.net/problem/13549
제출했다가 99%에서 틀려서 허거덩하면서 확인했다.
x+1을 먼저 실행할 경우 값이 오염받을 수 있어 x-1을 먼저 해줘야 했다.
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <string>
#include <map>
#include <limits.h>
#include <queue>
#include <set>
#include <math.h>
#include <stack>
#include <deque>
#include <string.h>
using namespace std;
int dist[100002] = {0};
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, k;
cin >> n >> k;
if (n >= k) {
cout << n - k << '\n';
return 0;
}
queue<int> q;
q.push(n);
// 0일 수도 있으니까 나중에 1빼주기
dist[n] = 1;
while (!q.empty()) {
int x = q.front();
q.pop();
if (x == k) {
cout << dist[x] - 1 << '\n';
return 0;
}
int tempX = x;
// 50000까지 모든 값 해주기
while (tempX <= 50000) {
if (dist[tempX * 2] != 0)
break;
dist[tempX * 2] = dist[x];
tempX *= 2;
q.push(tempX);
if (tempX == k) {
cout << dist[k] - 1 << '\n';
return 0;
}
}
// -1은 오염받지 않으니까 먼저 해준다.
if (!dist[x - 1] && x - 1 >= 0) {
dist[x - 1] = dist[x] + 1;
q.push(x - 1);
}
if (!dist[x + 1]) {
dist[x + 1] = dist[x] + 1;
q.push(x + 1);
}
}
cout << dist[k] - 1 << '\n';
return 0;
}
'PS > BOJ' 카테고리의 다른 글
[백준] 9466. 텀 프로젝트(c++) (0) | 2025.03.11 |
---|---|
[백준] 2206. 벽 부수고 이동하기(c++) (0) | 2025.03.11 |
[백준] 1074. Z(c++) (0) | 2025.03.02 |
[백준] 11729. 하노이 탑 이동 순서(c++) (0) | 2025.03.02 |
[백준] 1629. 곱셈(c++) (0) | 2025.03.02 |