๋ณธ๋ฌธ์œผ๋กœ ๋ฐ”๋กœ๊ฐ€๊ธฐ
728x90
๐Ÿ”—๋ฌธ์ œ ๋ณด๋Ÿฌ๊ฐ€๊ธฐ
 

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

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

www.acmicpc.net

 

๐Ÿง‘‍๐Ÿ’ปํ’€์ด ๊ณผ์ •

 

์–ผ๋งˆ ์ „์— ๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜(Dijkstra Algorithm)์„ ๊ณต๋ถ€ํ–ˆ์—ˆ์œผ๋‹ˆ, ๋จธ๋ฆฟ ์†์—์„œ ์ธ์ถœํ•˜๋Š” ์—ฐ์Šต์„ ์œ„ํ•ด ๋น„์Šทํ•œ ์œ ํ˜•์˜ ๋ฌธ์ œ๋ฅผ ํ•˜๋‚˜ ํ’€์–ด๋ดค์Šต๋‹ˆ๋‹ค. ์šฐ๋ฆฌ ๋ง์ด ์–ด๋ ค์šด ๊ฑด์ง€, ์ œ๊ฐ€ ๋ฉ์ฒญํ•œ ๊ฑด์ง€ ๋ชจ๋ฅด๊ฒ ์ง€๋งŒ ๋งค๋ฒˆ ํ—ท๊ฐˆ๋ฆฌ๋Š” ๊ฒƒ ๊ฐ™์•„์š”... ๊ทธ๋ž˜์„œ ์—ฐ์Šต์žฅ์— ๊ทธ๋ฆผ ๊ทธ๋ ค๊ฐ€๋ฉฐ ํ’‰๋‹ˆ๋‹ค. ( "distances[v] vs distances[u] + nextCost"  ๐Ÿ‘‰๐Ÿป  ์ด๊ฒŒ ์ ค ํ—ท๊ฐˆ๋ฆฝ๋‹ˆ๋‹ค. )

 

์•Œ๊ณ ๋ฆฌ์ฆ˜์€ ๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ทธ ์ž์ฒด์ด๋‹ˆ, ๐Ÿ”—[BOJ] 13549๋ฒˆ | ์ˆจ๋ฐ”๊ผญ์งˆ 3 ์— ์ ์—ˆ๋˜ ํ’€์ด ๊ทธ๋Œ€๋กœ ์ ์šฉํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

 

โœ๏ธ ์†Œ์Šค ์ฝ”๋“œ ๋ฐ ๊ฒฐ๊ณผ

#include <iostream>
#include <vector>
#include <queue>

using namespace std;
using uint32 = unsigned int;
using Route = pair<uint32, uint32>;

#define FAST_IO ios::sync_with_stdio(false); cout.tie(NULL); cin.tie(NULL);
#define INF 4000000000

void Dijkstra(const vector<vector<Route>>& routes, vector<uint32>& distances, uint32 start) {
    priority_queue<Route, vector<Route>, greater<Route>> buses;
    distances[start] = 0;
    buses.emplace(0, start);

    while (!buses.empty()) {
        Route bus = buses.top();
        uint32 nextCityCost = bus.first;
        uint32 nextCity = bus.second;
        buses.pop();

        if (distances[nextCity] < nextCityCost)
            continue;

        for (const auto& route : routes[nextCity]) {
            uint32 newCityCost = route.first;
            uint32 newCity = route.second;
            uint32 newPathCost = distances[nextCity] + newCityCost;

            if (newPathCost < distances[newCity]) {
                distances[newCity] = newPathCost ;
                buses.emplace(newPathCost, newCity);
            }
        }
    }
}

int main() {
    FAST_IO
    int N, M;
    cin >> N >> M;

    uint32 from, to, cost;
    vector<vector<Route>> busRouteInfo(N + 1, vector<Route>());
    for (int i = 0; i < M; i++) {
        cin >> from >> to >> cost;
        busRouteInfo[from].emplace_back(cost, to);
    }

    vector<uint32> distances(N + 1, INF);
    uint32 start, destination;
    cin >> start >> destination;

    Dijkstra(busRouteInfo, distances, start);
    cout << distances[destination];

    return 0;
}

 

 

728x90
๋ฐ˜์‘ํ˜•