๋ฐฑ์ค€/C++

[๋ฐฑ์ค€/C++] 1753๋ฒˆ ์ตœ๋‹จ๊ฒฝ๋กœ

yulee_to 2022. 7. 15. 01:29

๋ฐฑ์ค€
๋ฐฑ์ค€
1753๋ฒˆ ์ตœ๋‹จ๊ฒฝ๋กœ


๐Ÿค”๋ฌธ์ œ ์ดํ•ด

์‹œ์ž‘์ ์—์„œ ๊ฐ ์ •์ ์„ ๋ฐฉ๋ฌธํ•˜๊ธฐ ์œ„ํ•ด ํ•„์š”ํ•œ ์ตœ์†Œ ๋น„์šฉ์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.


๐Ÿ’ก์ฒซ๋ฒˆ์งธ ์•„์ด๋””์–ด

๋ฌธ์ œ๊ฐ€ ๊ทธ๋ƒฅ ๋”ฑ ๋‹ค์ต์ŠคํŠธ๋ผ ๋ฌธ์ œ๋ผ ๋‹ค์ต์ŠคํŠธ๋ผ๋ฅผ ์ด์šฉํ–ˆ๋‹ค.

 

๐Ÿ”ฅํ’€์ด๐Ÿ”ฅ

๋‹ค์ต์ŠคํŠธ๋ผ๋ฅผ ๊ทธ๋Œ€๋กœ ๊ตฌํ˜„ํ•˜์˜€๊ณ , ๋‹ค์Œ ์ •์ ๊นŒ์ง€์˜ ๊ฑฐ๋ฆฌ๋ฅผ ์šฐ์„ ์ˆœ์œ„ํ์— ๋„ฃ์–ด์ฃผ๊ธฐ ์ „์— ์ด๋ฏธ ๊ทธ ์ •์ ๊นŒ์ง€ ์ตœ์†Œ๊ฑฐ๋ฆฌ๋ณด๋‹ค ํฌ๋ฉด ํ์— ๋„ฃ์–ด์ฃผ์ง€ ์•Š๊ณ  continue๋ฅผ ํ•ด์ฃผ์—ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์šฐ์„ ์ˆœ์œ„ํ์— ๋“ค์–ด์žˆ๋Š” ์ •์ ์ด ์ด๋ฏธ ์ตœ์†Œ๊ฑฐ๋ฆฌ๊ฐ€ ํ™•์ •๋˜์—ˆ๋‹ค๋ฉด ๊ทธ ๋•Œ์—๋„ continue๋ฅผ ํ•ด์ค˜์„œ ๋ถˆํ•„์š”ํ•œ ์—ฐ์‚ฐ์„ ์ค„์—ฌ์ฃผ์—ˆ๋‹ค. 

 


์•„๋ž˜๋Š” ์ œ์ถœํ•œ ์ฝ”๋“œ์ด๋‹ค.

#include <iostream>
#include <queue>

using namespace std;
#define INF 100000000

int dist[20002], v, e, k;

int main() {
    cin.tie(nullptr);
    cout.tie(nullptr);
    ios::sync_with_stdio(false);

    cin >> v >> e >> k;

    vector<vector<pair<int, int>>> edge(v+1);
    int a, b, c;
    for (int i = 0; i < e; i++) {
        cin >> a >> b >> c;
        edge[a].push_back({b, c});
    }

    for (int i = 1; i <= v; i++) {
        dist[i] = INF;
    }
    dist[k] = 0;

    priority_queue<pair<int, int>> pq;

    pq.push({0, k});

    while (!pq.empty()) {
        int weight = -pq.top().first;
        int vertex = pq.top().second;
        pq.pop();
        if (weight > dist[vertex])
            continue;

        for (auto u: edge[vertex]) {
            int n = u.first;
            int w = u.second + weight;
            if (dist[n] <= w) continue;
            pq.push({-w, n});
            dist[n] = w;
        }
    }

    for (int i = 1; i <= v; i++) {
        if (dist[i] == INF) cout << "INF\n";
        else cout << dist[i] << "\n";
    }
}

 

728x90