PS/BOJ
[백준] 1697. 숨바꼭질(c++)
backend 개발자 지망생
2025. 2. 24. 10:38
https://www.acmicpc.net/problem/1697
범위를 넘어서는 부분을 분기처리 하지 않아서 outofbounds error가 났다.
항상 가능하지 않은 부분은 어디까지 인가 생각하면서 구현하자.
#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>
using namespace std;
// int dx[4] = {0, 0, -1, 1};
// int dy[4] = {-1, 1, 0, 0};
int dis[2000001] = {0};
int visited[2000001] = {0};
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, k, ans = 100001;
int cnt = 0;
cin >> n >> k;
if (k <= n) {
cout << n - k;
return 0;
}
queue<int> q;
// 시작점
q.push(n);
// 종료 조건은 n == k일 때
while (!q.empty()) {
int x = q.front();
q.pop();
if (x - 1 == k || x + 1 == k || (2 * x) == k) {
cout << dis[x] + 1;
break;
}
// 3가지 분기
if (x - 1 >= 0 && !visited[x - 1]) {
dis[x - 1] = dis[x] + 1;
visited[x - 1] = true;
q.push(x - 1);
}
if (!visited[x + 1]) {
dis[x + 1] = dis[x] + 1;
visited[x + 1] = true;
q.push(x + 1);
}
if (!visited[2 * x] && 2 * x <= 200001) {
dis[2 * x] = dis[x] + 1;
visited[2 * x] = true;
q.push(2 * x);
}
}
return 0;
}