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

[๋ฐฑ์ค€,c++] 1238๋ฒˆ - ํŒŒํ‹ฐ

by dkswnkk 2021. 11. 2.
 

1238๋ฒˆ: ํŒŒํ‹ฐ

์ฒซ์งธ ์ค„์— N(1 ≤ N ≤ 1,000), M(1 ≤ M ≤ 10,000), X๊ฐ€ ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„๋˜์–ด ์ž…๋ ฅ๋œ๋‹ค. ๋‘ ๋ฒˆ์งธ ์ค„๋ถ€ํ„ฐ M+1๋ฒˆ์งธ ์ค„๊นŒ์ง€ i๋ฒˆ์งธ ๋„๋กœ์˜ ์‹œ์ž‘์ , ๋์ , ๊ทธ๋ฆฌ๊ณ  ์ด ๋„๋กœ๋ฅผ ์ง€๋‚˜๋Š”๋ฐ ํ•„์š”ํ•œ ์†Œ์š”์‹œ๊ฐ„ Ti๊ฐ€ ๋“ค์–ด

www.acmicpc.net

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

using namespace std;
int N, M, X; //N=๋งˆ์„(๋…ธ๋“œ) M=๋„๋กœ(๊ฐ„์„ ) X=๋„์ฐฉ์ง€
int d[1001];    //์ตœ์†Œ ์‹œ๊ฐ„์„ ๊ธฐ๋กํ•ด๋‘๋Š” ํ…Œ์ด๋ธ”
int result[1001]; //i->x->i์˜ ์‹œ๊ฐ„์„ ๊ธฐ๋กํ•˜๋Š” ํ…Œ์ด๋ธ”
int ans = 0;
vector<pair<int, int>>graph[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 neighborDist = dist+graph[now][i].second;
            int neighbor = graph[now][i].first;

            if (neighborDist < d[neighbor]) {
                d[neighbor] = neighborDist;
                pq.push({ neighborDist,neighbor });
            }
        }
    }
}

void reset() {
    fill(d, d + 1001, INF);
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cin >> N >> M >> X;

    for (int i = 0; i < M; i++) {
        int a, b, c; cin >> a >> b >> c;
        graph[a].push_back({ b,c });    //a์—์„œ b๊นŒ์ง€ ๊ฐ€๋Š”๋ฐ c๋งŒํผ์˜ ์‹œ๊ฐ„์ด ๋“ ๋‹ค.
    }

    for (int i = 1; i <= N; i++) {    //i->X ๊นŒ์ง€ ์‹œ๊ฐ„ ๊ธฐ๋ก
        reset();                //๋งค ํƒ์ƒ‰๋งˆ๋‹ค ์ดˆ๊ธฐํ™” ์‹œ์ผœ์ค€๋‹ค.
        dijkstra(i);
        result[i] = d[X];
    }
        reset();
        dijkstra(X);    //์™•๋ณต์„ ํ•ด์•ผ ํ•˜๋‹ˆ๊นŒ X์—์„œ ๊ฐ ๋งˆ์„(๋…ธ๋“œ)=i ๊นŒ์ง€ ๊ฑธ๋ฆฌ๋Š” d[] ํ…Œ์ด๋ธ”์— ๊ธฐ๋ก
    for (int i = 1; i <= N; i++) {    //X->i๊นŒ์ง€์˜ ์‹œ๊ฐ„์„ i->X ๊นŒ์ง€ ๊ฑธ๋ฆฌ๋Š” ์‹œ๊ฐ„์— ๋”ํ•จ. 
        result[i] += d[i];
    }
    for (int i = 1; i <= N; i++) {    //i->X->i ๊นŒ์ง€ ๊ฑธ๋ฆฌ๋Š” ์‹œ๊ฐ„์˜ ์ตœ๋Œ“๊ฐ’์„ ๊ตฌํ•œ๋‹ค.
        ans = max(ans, result[i]);
    }
    cout << ans;

}

๋Œ“๊ธ€