Notice
Recent Posts
Recent Comments
Link
Be a developer
백준 13913 숨바꼭질 4 본문
앞선 숨바꼭질 문제와 같다.
추가된 것이 있다면 답을 찾아가는 경로를 출력해야 한다.
그래서 경로를 저장하기 위한 배열 d를 하나 더 둔다.
도착지에서부터 출발지로 가면서 stack에 쌓은 후 pop하면서 출력한다.
물론 재귀 함수 호출을 통해서 출력해도 된다.
코드는 아래와 같다.
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
|
#include <iostream>
#include <queue>
#include <stack>
using namespace std;
int time[100001];
int d[100001];
int main(int argc, char** argv) {
int n, k;
cin >> n >> k;
for (int i = 0; i < 100001; i++)time[i] = -1;
queue<int> q;
q.push(n);
time[n] = 0;
while (!q.empty()) {
int position = q.front();
q.pop();
int prev = position - 1;
int next = position + 1;
int jump = position * 2;
if (prev >= 0) {
if (time[prev] == -1) {
time[prev] = time[position] + 1;
d[prev] = position;
q.push(prev);
}
}
if (next < 100001) {
if (time[next] == -1) {
time[next] = time[position] + 1;
d[next] = position;
q.push(next);
}
}
if (jump< 100001) {
if (time[jump] == -1) {
time[jump] = time[position] + 1;
d[jump] = position;
q.push(jump);
}
}
}
printf("%d\n", time[k]);
stack<int> s;
s.push(k);
while (k != n) {
s.push(d[k]);
k = d[k];
}
while (!s.empty()) {
int x = s.top();
s.pop();
printf("%d ", x);
}
return 0;
}
|
cs |
'알고리즘' 카테고리의 다른 글
백준 2251 물통 (0) | 2019.04.09 |
---|---|
백준 9019 DSLR (0) | 2019.04.08 |
백준 3055 탈출 (0) | 2019.04.08 |
백준 2206 벽 부수고 이동하기 (0) | 2019.04.08 |
백준 1261 알고스팟 (0) | 2019.04.08 |
Comments