forked from b-chae/AlgorithmStudy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path13549.cpp
More file actions
58 lines (49 loc) · 1.13 KB
/
Copy path13549.cpp
File metadata and controls
58 lines (49 loc) · 1.13 KB
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
#include <iostream>
#include <list>
using namespace std;
int N, K;
bool visited[100001];
list<pair<int, int>> bfsQueue;
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cin >> N >> K;
int i;
bfsQueue.push_back({N, 0});
for (i = N * 2; i <= 100000 && i != 0; i *= 2)
{
bfsQueue.push_back({i, 0});
}
while (!bfsQueue.empty())
{
int n = bfsQueue.front().first;
int t = bfsQueue.front().second;
bfsQueue.pop_front();
if (!visited[n])
{
visited[n] = true;
if (n == K)
{
cout << t << "\n";
return 0;
}
for (i = n * 2; i <= 100000 && i != 0; i *= 2)
{
if (!visited[i])
{
bfsQueue.push_front({i, t});
}
}
if (n < 100000 && !visited[n + 1])
{
bfsQueue.push_back({n + 1, t + 1});
}
if (n > 0 && !visited[n - 1])
{
bfsQueue.push_back({n - 1, t + 1});
}
}
}
return 0;
}