https://www.acmicpc.net/problem/13913
#include <bits/stdc++.h>
using namespace std;
//숨바꼭질 4
int main(void) {
queue<int> q;
int n, m, visited[10000] = {0,}, time[10000] = {0,};
cin >> n >> m;
q.push(n);
visited[n] = 1;
while (!q.empty()) {
int now = q.front();
q.pop();
if (now == m) {
printf("%d\n", time[m]);
break;
}
if (time[now-1] >= 0 && visited[now-1] == 0) {
q.push(now-1);
visited[now-1] = 1;
time[now-1] = time[now] + 1;
}
if (time[now+1] <= 10000 && visited[now+1] == 0) {
q.push(now+1);
visited[now+1] = 1;
time[now+1] = time[now] + 1;
}
if (time[now*2] <= 10000 && visited[now*2] == 0) {
q.push(now*2);
visited[now*2] = 1;
time[now*2] = time[now] + 1;
}
}
int path[10000], index = 0;
int now = m;
path[index] = now;
index++;
while(now != n) {
//printf("===%d \n", now);
if (now-1 >= 0 && visited[now-1] == 1 && time[now-1] == time[now]-1) {
now = now - 1;
}
else if (now+1 <= 10000 && visited[now+1] == 1 && time[now+1] == time[now]-1) {
now = now+1;
}
else if (now % 2 == 0 && visited[now/2] == 1 && time[now/2] == time[now]-1) {
now = now/2;
}
path[index] = now;
index++;
}
//return 0;
for (int i=index-1; i>=0; i--) {
printf("%d ", path[i]);
}
return 0;
}
'정보올림피아드-KOI > BOJ' 카테고리의 다른 글
백준 숫자카드 - 이분탐색 (0) | 2022.03.18 |
---|---|
백준 1,2,3 더하기 (브루트 포스) (0) | 2022.03.18 |
백준 일곱 난쟁이 (0) | 2022.03.14 |
백준 2×n 타일링 2 (0) | 2022.03.14 |
백준 꿀따기 21758번 (11점 ) (0) | 2022.03.11 |