[BOJ] 13913 숨바꼭질 4

Time Lapse :35min 40sec

13913.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
#include <iostream>
#include <memory.h>
#include <queue>
#include <stack>
#define INF 100000
using namespace std;
int arr[INF + 1];
stack<int> ans;
int n, k;
int bfs() {
memset(arr, -1, sizeof(arr));
arr[n] = 0;
queue<int> q;
q.push(n);
while(!q.empty()) {
int val = q.front();
q.pop();
if(val + 1 <= INF && arr[val + 1] == -1) {
arr[val + 1] = arr[val] + 1;
q.push(val + 1);
if(val + 1 == k) return arr[k];
}
if(val * 2 <= INF && arr[val * 2] == -1) {
arr[val * 2] = arr[val] + 1;
q.push(val * 2);
if(val * 2 == k) return arr[k];
}
if(val - 1 >= 0 && arr[val - 1] == -1) {
arr[val - 1] = arr[val] + 1;
q.push(val - 1);
if(val - 1 == k) return arr[k];
}
}
}
void makeAns() {
ans.push(k);
while(arr[ans.top()]) {
if(!(ans.top() & 1) && (arr[ans.top() / 2] == arr[ans.top()] - 1))
ans.push(ans.top() / 2);
else if(ans.top() + 1 <= INF && arr[ans.top() + 1] == arr[ans.top()] - 1)
ans.push(ans.top() + 1);
else if(ans.top() - 1 >= 0 && arr[ans.top() - 1] == arr[ans.top()] - 1)
ans.push(ans.top() - 1);
}
}
int main() {
scanf("%d %d",&n,&k);
if(n == k) {
printf("0\n%d",n);
exit(0);
}
memset(arr, -1, sizeof(arr));
printf("%d\n",bfs());
makeAns();
while(!ans.empty()) {
printf("%d ",ans.top());
ans.pop();
}
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2020/09/24/PS/BOJ/13913/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.