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

[๋ฐฑ์ค€,c++] 14284๋ฒˆ - ๊ฐ„์„  ์ด์–ด๊ฐ€๊ธฐ2

by dkswnkk 2021. 11. 6.
 

14284๋ฒˆ: ๊ฐ„์„  ์ด์–ด๊ฐ€๊ธฐ 2

์ •์  n๊ฐœ, 0๊ฐœ์˜ ๊ฐ„์„ ์œผ๋กœ ์ด๋ฃจ์–ด์ง„ ๋ฌด๋ฐฉํ–ฅ ๊ทธ๋ž˜ํ”„๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๊ทธ๋ฆฌ๊ณ  m๊ฐœ์˜ ๊ฐ€์ค‘์น˜ ๊ฐ„์„ ์˜ ์ •๋ณด๊ฐ€ ์žˆ๋Š” ๊ฐ„์„ ๋ฆฌ์ŠคํŠธ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๊ฐ„์„ ๋ฆฌ์ŠคํŠธ์— ์žˆ๋Š” ๊ฐ„์„  ํ•˜๋‚˜์”ฉ ๊ทธ๋ž˜ํ”„์— ์ถ”๊ฐ€ํ•ด ๋‚˜๊ฐˆ ๊ฒƒ์ด๋‹ค.

www.acmicpc.net

#include <iostream>
#include <vector>
#include <queue>
#define INF 1e9 //๋ฌดํ•œ๋Œ€๋ฅผ ์˜๋ฏธํ•˜๋Š” ๊ฐ’์œผ๋กœ 10์–ต์„ ์ง€์ •.
using namespace std;

vector<pair<int, int>>graph[5002];
int n, m, start, fin; //n=์ •์ ์˜ ๊ฐœ์ˆ˜ m=๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜    start=์‹œ์ž‘ ๋…ธ๋“œ fin=๋ ๋…ธ๋“œ
int d[5002]; //๊ฐ€์ค‘์น˜๋ฅผ ์ €์žฅํ•˜๋Š” ํ…Œ์ด๋ธ”


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;
                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๋งŒํผ์˜ ๊ฐ€์ค‘์น˜๊ฐ€ ๋“ ๋‹ค.
        graph[b].push_back({ a,c });        //๋ฌด๋ฐฉํ–ฅ(์–‘๋ฐฉํ–ฅ) ์ฒ˜๋ฆฌ
    }
    fill(d, d + 5001, INF);

    cin >> start >> fin;
    dijkstra(start);
    cout << d[fin];
}

๋Œ“๊ธ€