|
| 1 | +#include <bits/stdc++.h> |
| 2 | +using namespace std; |
| 3 | +typedef long long ll; |
| 4 | +struct Node { |
| 5 | + int x; |
| 6 | + ll weight; |
| 7 | +}; |
| 8 | +struct Edge { |
| 9 | + int v,w,idx; |
| 10 | +}; |
| 11 | +struct Compare { |
| 12 | + bool operator()(const Node &a, const Node &b) { |
| 13 | + return a.weight > b.weight; |
| 14 | + } |
| 15 | +}; |
| 16 | + |
| 17 | +void solve(){ |
| 18 | + int N, M; cin >> N >> M;N++; |
| 19 | + assert(N>1); |
| 20 | + assert(M>1); |
| 21 | + |
| 22 | + int S=1,E=N-1; |
| 23 | + vector<vector<Edge>> edges(N); |
| 24 | + for (int i = 0; i <M;i++) { |
| 25 | + int u,v,w; cin >> u >> v >> w; |
| 26 | + edges[u].push_back({v,w,i}); |
| 27 | + edges[v].push_back({u,w,i}); |
| 28 | + } |
| 29 | + |
| 30 | + vector<vector<pair<int,int>>> parntes(N); |
| 31 | + |
| 32 | + priority_queue<Node, vector<Node>, Compare> q; q.push({S,0}); |
| 33 | + |
| 34 | + ll distances[N]; memset(distances, -1, sizeof(distances)); distances[S]=0; |
| 35 | + vector<vector<int>> results; |
| 36 | + while (q.size()) { |
| 37 | + auto [x, weight] = q.top(); q.pop(); |
| 38 | + for (auto [nx, w, idx] : edges[x]) { |
| 39 | + if (distances[nx] > weight + w) parntes[nx].clear(); |
| 40 | + |
| 41 | + if (distances[nx] == -1 || distances[nx] > weight + w) { |
| 42 | + parntes[nx].push_back({x,idx}); |
| 43 | + distances[nx] = weight + w; |
| 44 | + q.push({nx, distances[nx]}); |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + bool blocked[M]; |
| 50 | + memset(blocked, 0, sizeof(blocked)); |
| 51 | + queue<int> q2; q2.push(E); |
| 52 | + while (q2.size()) { |
| 53 | + auto p = q2.front(); q2.pop(); |
| 54 | + for (auto [x, idx] : parntes[p]) { |
| 55 | + blocked[idx] = true; |
| 56 | + q2.push(x); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + |
| 61 | + memset(distances, -1, sizeof(distances)); |
| 62 | + distances[S]=0; |
| 63 | + q.push({S,0}); |
| 64 | + while(q.size()) { |
| 65 | + auto [x, weight] = q.top(); q.pop(); |
| 66 | + for (auto [nx, w, idx] : edges[x]) { |
| 67 | + if (blocked[idx]) continue; |
| 68 | + |
| 69 | + if (distances[nx] == -1 || distances[nx] > weight+w) { |
| 70 | + distances[nx] = weight+w; |
| 71 | + q.push({nx, distances[nx]}); |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + cout << distances[E]; |
| 77 | +} |
| 78 | + |
| 79 | +int main() { |
| 80 | + cin.tie(0) -> sync_with_stdio(0); |
| 81 | + |
| 82 | + solve(); |
| 83 | + |
| 84 | + return 0; |
| 85 | +} |
0 commit comments