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

[๋ฐฑ์ค€,c++] 1504๋ฒˆ - ํŠน์ •ํ•œ ์ตœ๋‹จ ๊ฒฝ๋กœ

by dkswnkk 2021. 11. 17.

๋ฌธ์ œ

 

1504๋ฒˆ: ํŠน์ •ํ•œ ์ตœ๋‹จ ๊ฒฝ๋กœ

์ฒซ์งธ ์ค„์— ์ •์ ์˜ ๊ฐœ์ˆ˜ N๊ณผ ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜ E๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. (2 ≤ N ≤ 800, 0 ≤ E ≤ 200,000) ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ E๊ฐœ์˜ ์ค„์— ๊ฑธ์ณ์„œ ์„ธ ๊ฐœ์˜ ์ •์ˆ˜ a, b, c๊ฐ€ ์ฃผ์–ด์ง€๋Š”๋ฐ, a๋ฒˆ ์ •์ ์—์„œ b๋ฒˆ ์ •์ ๊นŒ์ง€ ์–‘๋ฐฉํ–ฅ ๊ธธ์ด ์กด

www.acmicpc.net

 

์ฝ”๋“œ

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


using namespace std;

int N, E, v1, v2;    //N=์ •์ ์˜ ๊ฐœ์ˆ˜, E=๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜,    v1,v2=๊ฑฐ์ณ์•ผ ํ•˜๋Š” ์ •์  ๋ฒˆํ˜ธ
vector<pair<int, int>>graph[801];    //๊ฐ ๋…ธ๋“œ์— ์—ฐ๊ฒฐ๋˜์–ด ์žˆ๋Š” ๋…ธ๋“œ์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ๋‹ด๋Š” ๋ฐฐ์—ด
int d[801];    //์ตœ๋‹จ ๊ฑฐ๋ฆฌ ํ…Œ์ด๋ธ”
int check[801];    //v1,v2๋ฅผ ๊ฑฐ์ณ ๊ฐ€๋Š” ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋ฅผ ์ €์žฅํ•˜๋Š” ํ…Œ์ด๋ธ”

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

void dijkstra(int start) {
    reset();
    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 >> E;

    for (int i = 0; i < E; i++) {
        int a, b, c; cin >> a >> b >> c;
        graph[a].push_back({ b,c });    //a์—์„œb๋กœ ๊ฐ€๋Š”๋ฐ c๋งŒํผ์˜ ๋น„์šฉ์ด ๋“ ๋‹ค.
        graph[b].push_back({ a,c });    //์–‘๋ฐฉํ–ฅ ์ฒ˜๋ฆฌ
    }
    cin >> v1 >> v2;

    /* ๊ณ ๋ ค ํ•ด์•ผ ํ•  ๊ฒฝ์šฐ์˜ ์ˆ˜
    1. a->v1->v2->b
    2. a->v2->v1->b
    */

    dijkstra(1);
    check[0] = d[v1];    //1->v1๊นŒ์ง€์˜ ๊ฑฐ๋ฆฌ
    check[1] = d[v2];    //1->v2๊นŒ์ง€์˜ ๊ฑฐ๋ฆฌ
    dijkstra(v1);
    check[2] = d[v2];    //v1->v2๊นŒ์ง€์˜ ๊ฑฐ๋ฆฌ
    check[3] = d[N];    //v1->N๊นŒ์ง€์˜ ๊ฑฐ๋ฆฌ
    dijkstra(v2);
    check[4] = d[N];    //v2->N๊นŒ์ง€์˜ ๊ฑฐ๋ฆฌ
    check[5] = d[v1];    //v2->v1๊นŒ์ง€์˜ ๊ฑฐ๋ฆฌ

    int ans = INF;
    ans = min(ans, check[0] + check[2] + check[4]);    //v1->v2
    ans = min(ans, check[1] + check[5] + check[3]);    //v2->v1

    if (ans == INF || check[2] == INF || check[5] == INF) cout << -1;
    else cout << ans;
}

๋Œ“๊ธ€