본문 바로가기

PS

백준 BOJ 31913 C++ 숨바꼭질 4

#include <bits/stdc++.h>
using namespace std;

int n, k, board[200002], dist[200002];

void solve() {
    cin >> n >> k;
    queue<int> q;
    memset(dist, -1, sizeof(dist));
    board[n] = -1;
    dist[n] = 0;
    q.push(n);
    while (!q.empty()) {
        int x = q.front();
        q.pop();
        int dx[] = {x - 1, x + 1, 2 * x};
        for (int dir = 0; dir < 3; ++dir) {
            int nx = dx[dir];
            if (nx >= 0 && nx < 200002) {
                if (dist[nx] == -1) {
                    dist[nx] = dist[x] + 1;
                    board[nx] = x;
                    if (nx == k) {
                        return;
                    }
                    q.push(nx);
                }
            }
        }
    }
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    solve();
    cout << dist[k] << '\n';
    stack<int> st;
    int i = k;
    while (i != -1) {
        st.push(i);
        i = board[i];
    }
    while (!st.empty()) {
        cout << st.top() << ' ';
        st.pop();
    }
    return 0;
}