๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/๋ฐฑ์ค€(BOJ)

[๋ฐฑ์ค€,c++] 11779๋ฒˆ - ์ตœ์†Œ๋น„์šฉ ๊ตฌํ•˜๊ธฐ2

by dkswnkk 2021. 10. 31.
 

11779๋ฒˆ: ์ตœ์†Œ๋น„์šฉ ๊ตฌํ•˜๊ธฐ 2

์ฒซ์งธ ์ค„์— ๋„์‹œ์˜ ๊ฐœ์ˆ˜ n(1≤n≤1,000)์ด ์ฃผ์–ด์ง€๊ณ  ๋‘˜์งธ ์ค„์—๋Š” ๋ฒ„์Šค์˜ ๊ฐœ์ˆ˜ m(1≤m≤100,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์…‹์งธ ์ค„๋ถ€ํ„ฐ m+2์ค„๊นŒ์ง€ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋ฒ„์Šค์˜ ์ •๋ณด๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋จผ์ € ์ฒ˜์Œ์—๋Š” ๊ทธ ๋ฒ„์Šค

www.acmicpc.net

#include <iostream>
#include <vector>
#include <queue>
#define INF 1e9 //๋ฌดํ•œ์„ ๋œปํ•˜๋Š” ๊ฐ’์œผ๋กœ 10์–ต์„ ์ง€์ •.

using namespace std;

vector<pair<int, int>>graph[1001];
int d[1001];//๋น„์šฉ์„ ์ €์žฅํ•ด๋‘๋Š” ํ…Œ์ด๋ธ”
int N, M, start, fin; //N=๋„์‹œ(๋…ธ๋“œ)์˜ ๊ฐœ์ˆ˜, M=๋ฒ„์Šค(๊ฐ„์„ )์˜ ๊ฐœ์ˆ˜ ,start=์‹œ์ž‘์ , fin=๋„์ฐฉ์ 
int route[1001]; //์ตœ์†Œ๋น„์šฉ์„ ๊ฐ–๋Š” ๊ฒฝ๋กœ๋ฅผ ๋ฐฉ๋ฌธํ•˜๋Š” ๋„์‹œ๋ฅผ ์ €์žฅํ•˜๋Š” ํ…Œ์ด๋ธ”




void dijkstra(int start) {
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>>pq;
    pq.push({ 0,start });    //์‹œ์ž‘์ ์˜ ๋น„์šฉ์€ 0
    d[start] = 0;
    while (!pq.empty()) {
        int dist = pq.top().first;
        int now = pq.top().second;
        pq.pop();

        if (d[now] < dist) continue;    //์ด๋ฏธ ์ฒ˜๋ฆฌ๋œ ๋…ธ๋“œ๋ผ๋ฉด ๋ฌด์‹œํ•œ๋‹ค.
        for (int i = 0; i < graph[now].size(); i++) {
            int neighbor = graph[now][i].first;
            int neighborDist = dist + graph[now][i].second;
            if (neighborDist < d[neighbor]) {
                d[neighbor] = neighborDist;
                route[neighbor] = now;    //๋ฐฉ๋ฌธํ•˜๋Š” ๋„์‹œ ์ €์žฅ.route[i]=๊ฒฝ๋กœ์—์„œ i๋…ธ๋“œ๋กœ ๊ฐ€๊ธฐ ๋ฐ”๋กœ ์ง์ „ ๋…ธ๋“œ
                pq.push({ neighborDist,neighbor });
            }
        }
    }
}


int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);

    cin >> N >> M;
    for (int i = 0; i < M; i++) {
        int a, b, c; cin >> a >> b >> c;    //๊ฐ„์„  ์ •๋ณด ์ž…๋ ฅ
        graph[a].push_back({ b,c });        // a์—์„œ b๊นŒ์ง€ ๊ฐ€๋Š”๋ฐ c๋งŒํผ์˜ ๋น„์šฉ ํ•„์š”
    }
    cin >> start >> fin;
    fill(d, d + 1001, INF);

    dijkstra(start);

    cout << d[fin] << "\n";    //์ตœ์†Œ๋น„์šฉ ์ถœ๋ ฅ
    vector<int>ans;
    int node = fin;

    while (node) {
        ans.push_back(node);
        node = route[node];    //๊ฒฝ๋กœ๋ฅผ ์—ญ์œผ๋กœ ์ €์žฅํ•˜๊ณ  1์ผ ๊ฒฝ์šฐ 0์ด๊ธฐ ๋•Œ๋ฌธ์— while ๋ฌธ ํƒˆ์ถœ
    }
    cout << ans.size() << '\n';
    for (int i = ans.size() - 1; i >= 0; i--) {    //์—ญ์ˆœ์œผ๋กœ ์ €์žฅ๋˜๋ฏ€๋กœ.
        cout << ans[i] << " ";
    }
}

๋Œ“๊ธ€