-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path13549.cpp
65 lines (62 loc) · 1.39 KB
/
13549.cpp
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include<iostream>
#include<queue>
using namespace std;
int n, k;
int visited[100001] = {0, };
void bfs();
int answer = 0;
queue<pair<int, int>> q;
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> n >> k;
q.push({n, 0});
visited[n] = 1;
bfs();
cout << answer;
}
void bfs(){
if(n == k){
answer = 0;
return;
}
while(!q.empty()){
int nowLo = q.front().first;
int time = q.front().second;
q.pop();
int location = nowLo;
while(location*2 <= 100000){
if(location == 0)break;
location *= 2;
if(location == k){
answer = time;
return;
}
if(visited[location] == 0){
visited[location] = 1;
q.push({location, time});
}
}
if(nowLo-1 >= 0){
if(nowLo-1 == k){
answer = time + 1;
return;
}
if(visited[nowLo-1] == 0){
visited[nowLo-1] = 1;
q.push({nowLo-1, time+1});
}
}
if(nowLo+1 <= k){
if(nowLo+1 == k){
answer = time + 1;
return;
}
if(visited[nowLo+1] == 0){
visited[nowLo+1] = 1;
q.push({nowLo+1, time+1});
}
}
}
}