๋ฐฑ์ค€/C++

[๋ฐฑ์ค€/C++] 17396๋ฒˆ ๋ฐฑ๋„์–ด

yulee_to 2022. 11. 11. 02:02

๋ฐฑ์ค€


๐Ÿค”๋ฌธ์ œ ์ดํ•ด

๋ง์€ ๊ฑฐ์ฐฝํ•˜์ง€๋งŒ ์ „ํ˜•์ ์ธ ๋‹ค์ต์ŠคํŠธ๋ผ ๋ฌธ์ œ์— ๋ฐฉ๋ฌธํ•  ์ˆ˜ ์—†๋Š” ๊ตฌ๊ฐ„์ด ์กด์žฌํ•œ๋‹ค๋Š” ๊ฒƒ๋งŒ ์ถ”๊ฐ€๋œ ๋ฌธ์ œ์ด๋‹ค.


๐Ÿ”ฅํ’€์ด๐Ÿ”ฅ

๋‹ค์ต์ŠคํŠธ๋ผ๋กœ ๊ตฌํ˜„์„ ํ•˜๊ณ  ์ƒ๋Œ€์˜ ์‹œ์•ผ์— ๋ณด์ด๋Š” ๋ถ„๊ธฐ์ ์€ ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š๋„๋ก ํ•ด์ฃผ๊ธฐ๋งŒ ํ•˜๋ฉด ๋œ๋‹ค. ๋„ฅ์„œ์Šค์˜ ๊ฒฝ์šฐ๋Š” ์‹œ์•ผ๊ฐ€ ๋ณด์ด์ง€๋งŒ ๊ฐˆ ์ˆ˜ ์žˆ์–ด์•ผ ํ•˜๋ฏ€๋กœ ๋”ฐ๋กœ 0์œผ๋กœ ์ฒ˜๋ฆฌํ•ด์ฃผ์—ˆ๋‹ค. 


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

using namespace std;
#define INF 10000000000

int n, m, a, b, t;
bool sight[100001];
vector<vector<pair<int, int>>> edge(100001);
long long dist[100001];

int main() {
    cin.tie(nullptr);
    cout.tie(nullptr);
    ios::sync_with_stdio(false);

    cin >> n >> m;
    for (int i = 0; i < n; i++) {
        cin >> sight[i];
        if (i == n - 1) sight[i] = false;
    }
    for (int i = 0; i < m; i++) {
        cin >> a >> b >> t;
        edge[a].push_back({b, t});
        edge[b].push_back({a, t});
    }
    for (int i = 0; i < n; i++) {
        dist[i] = INF;
    }
    dist[0] = 0;
    priority_queue<pair<long long, int>> pq;
    pq.push({0, 0});

    while (!pq.empty()) {
        int now = pq.top().second;
        long long time = -pq.top().first;
        pq.pop();

        if (dist[now] < time) continue;
        dist[now] = time;

        for (auto x: edge[now]) {
            long long next_time = time + x.second;
            int next = x.first;
            if (sight[next]) continue;
            if (dist[next] <= next_time) continue;
            dist[next] = next_time;
            pq.push({-next_time, next});
        }
    }
    if (dist[n - 1] == INF) cout << -1 << "\n";
    else cout << dist[n - 1] << "\n";

}
728x90