본문 바로가기
백준

[C++] 백준 13913 숨바꼭질 4 [Gold4]

by MINU.SHINNNN 2023. 1. 20.

풀이

1. 전반적인 풀이는 숨바꼭질 3 풀이와 동일하다. https://minuuu.tistory.com/33

 

[C++] 백준 13549 숨바꼭질 3 [Gold5]

풀이 1. 점 n에서 점 k로 갈 때 최소 연산횟수를 알고싶다. 2. 연산횟수 = 거리 로 생각하고 다익스트라 알고리즘을 돌리면 해결할 수 있다. 3. Info 구조체의 dis 변수에 연산횟수를 저장하고, 우선순

minuuu.tistory.com

2. 이 때, 최단 경로로 가는 점들을 기록하는 과정이 필요하다.

3. prev_ 벡터를 사용해서 next 점이 가리키는 곳에 현재 점을 저장하도록 한다. prev_[next] = curr;

4. 즉, next 에 도달 할 수 있는 이전 값은 curr 이고, curr 은 항상 최소값으로 갱신되어 있다.

5. prev_[curr] = next 가 되면 next 가 갱신될 때 prev_[curr] 값이 계속 변하게 된다. 

6. 답을 찾았으면, 스택을 사용해서 방문점을 뒤집어서 출력한다.

리뷰

1. prev_[n] = n; 처리를 하지 않으면 1 1 같은 상황에서 prev[1] = -1 이므로 메모리 초과 오답이 된다.

#include <iostream>
#include <climits>
#include <queue>
#include <stack>

using namespace std;

int n, k;
int d[3] = {0, 1, -1};
vector<int> dist(100001, INT_MAX);
vector<int> prev_(100001, -1);

struct Info{
    int curr;
    int dis;
    Info (int a, int b) {
        curr = a;
        dis = b;
    }
    bool operator<(const Info& x) const {
        return dis > x.dis;
    }
};

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);
    // freopen("13913.txt", "r", stdin);

    cin >> n >> k;
    priority_queue<Info> pq;

    pq.push(Info(n, 0));
    dist[n] = 0;
    prev_[n] = n;
    while (!pq.empty()) {
        int curr = pq.top().curr;
        int dis = pq.top().dis;
        pq.pop();
        
        if (dis > dist[curr]) continue;
        
        if (curr == k) {
            cout << dis << "\n"; ;
            int c = k;
            stack<int> stk;
            stk.push(c);
            while (true) {
                if (c == n) {
                    while (!stk.empty()) {
                        int v = stk.top();
                        stk.pop();
                        cout << v << " ";
                    }  
                    exit(0);   
                }
                
                c = prev_[c];
                stk.push(c);
            }
        }

        int next = 0;
        int next_dist = 0;
        for (int i=0; i<3; i++) {
            if (i == 0) {
                next = curr*2;
                next_dist = dis+1;
            }
            else {
                next = curr + d[i];
                next_dist = dis+1;
            }

            if (next < 0 || next > 100001) continue;
            if (dist[next] > next_dist) {
                prev_[next] = curr;
                dist[next] = next_dist;
                pq.push(Info(next, next_dist));    
            }
        }
    }

    return 0;
}