1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| #include <iostream> #include <bits/stdc++.h> #define LOCAL #define int long long #define MAXN 10020 #define INF 2100000000 using namespace std; struct Edge{ int v, c; Edge(): v(0), c(0) {} Edge(int _v, int _c): v(_v), c(_c) {} };
struct Status{ int v, c; Status(): v(0), c(0) {} Status(int _v, int _c): v(_v), c(_c) {}
bool operator < (const Status& other) const{ return c < other.c; } };
int c, v; int a, b, cost; vector<Edge> edge[MAXN]; int dist[MAXN];
void dijkstra(int root){ priority_queue<Status> q; q.push({root,0}); dist[root] = 0;
int cost; while(!q.empty()){ Status node = q.top(); q.pop(); for(auto it: edge[node.v]){ cost = dist[node.v] + it.c; if(cost < dist[it.v]){ q.push({it.v, cost}); dist[it.v] = cost; } } } }
int32_t main() { #ifdef LOCAL freopen("in1.txt", "r", stdin); freopen("out.txt", "w", stdout); #endif while(cin >> c >> v){ for(int i = 1; i <= c; i++){ edge[i].clear(); dist[i] = INF; dist[i] = -INF; } for(int i = 0; i < v; i++){ cin >> a >> b >> cost; edge[a].push_back({b,cost}); edge[b].push_back({a,cost}); } dijkstra(root); if(dist[x] == INF) cout << "-1\n"; else cout << dist[x] << "\n"; } return 0; }
|