BOJ13549_์ˆจ๋ฐ”๊ผญ์งˆ3

๋‹ค์ต์ŠคํŠธ๋ผ ์‚ฌ์šฉํ•œ๋‹ค๊ณ  ๋ฌด์กฐ๊ฑด ์ด์ค‘ vector ๋„ฃ์„ ํ•„์š” ์—†์Œ.

์ด ๋ฌธ์ œ์˜ ๊ฒฝ์šฐ graph์— ๊ฐ๊ฐ 3๊ฐœ์˜ ๊ฐ„์„  ๋„ฃ์—ˆ๋”๋‹ˆ runtime error

graph ๋Œ€์‹  ์กฐ๊ฑด๋ฌธ์œผ๋กœ ๋ฐ”๊ฟจ๋”๋‹ˆ ๋ฉ”๋ชจ๋ฆฌ ์ดˆ๊ณผ  ์•ˆ๋‚จ

 

์ดํ›„ ๋˜ ํ‹€๋ ธ๋Š”๋ฐ if(b > k * 2) ๋ผ๋Š” ์ด์ƒํ•œ ์กฐ๊ฑด๋ฌธ ๋„ฃ์–ด์„œ ํ‹€๋ฆผ

 

// graph ์— ๊ฐ๊ฐ 3๊ฐœ์˜ ๊ฐ„์„  ๋„ฃ์œผ๋ฉด runtime error
// graph ๋Œ€์‹  ์กฐ๊ฑด๋ฌธ์œผ๋กœ bad alloc ์—†์•ฐ
// if(b > k * 2) ๋ผ๋Š” ์ด์ƒํ•œ ์กฐ๊ฑด๋ฌธ ๋„ฃ์–ด์„œ ํ‹€๋ฆผ

#include <iostream>
#include <queue>
#include <vector>
#define INF int(1e5)

using namespace std;

struct Edge {
    int to;
    int cost;
};

struct cmp {
    bool operator() (Edge a, Edge b) {
        if (a.cost <= b.cost) return false;
        else return true;
    } 
};

int n, k;
int d[100001];
// ๊ฐ ๋…ธ๋“œ๋งˆ๋‹ค ๊ฐ„์„ ์ด 3๊ฐ€์ง€ ์žˆ๋‹ค๊ณ  ๊ฐ€์ •
// +1, -1 : ๊ฐ€์ค‘์น˜ +1
// *2 : ๊ฐ€์ค‘์น˜ 0

void dijkstra() {
    priority_queue<Edge, vector<Edge>, cmp> pq;
    pq.push({n, 0});        // ์ˆ˜๋นˆ์˜ ์œ„์น˜
    d[n] = 0;

    int X[2] = {-1, 1};

    while(!pq.empty()) {
        Edge cur = pq.top(); //ํ˜„์žฌ ์œ„์น˜, ํ˜„์žฌ ์‹œ๊ฐ„
        pq.pop();

        if (d[cur.to] < cur.cost) continue;

        int b, b_cost;
        for(int i = 0; i < 3; i++) {
            if (i == 2) {
                b = cur.to * 2;
                b_cost = cur.cost;
            } else {
                b = cur.to + X[i];
                b_cost = cur.cost + 1;
            }
            if (b < 0 || b > 100000) continue;
            if (d[b] <= b_cost) continue;

            d[b] = b_cost;
            pq.push({b, b_cost});
        }
    }
}


int main(void) {
    ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);

    cin >> n >> k;
    
    // ๋น„์šฉ ๋ฐฐ์—ด ์ดˆ๊ธฐํ™”
    for (int i = 0; i <= 100000; i++) {  
        d[i] = INF; 
    }

    dijkstra();

    cout << d[k] << endl;
}