signedmain() { cin >> n >> m; memset(g, 0x3f, sizeof g);//初始化两点距离数组 while (m--) { int a, b, c; cin >> a >> b >> c; g[a][b] = min(g[a][b], c);//两点有多条赋权边,因此保留最短 } int t = dijkstra(); printf("%d", t); }
#include<bits/stdc++.h> usingnamespace std; typedef pair<int, int> PII; constint N = 150010; int n, m; int e[N], w[N], h[N], ne[N], idx; int dist[N]; bool st[N];
voidadd(int a, int b, int c) { e[idx] = b; w[idx] = c;//赋权边 ne[idx] = h[a]; h[a] = idx++; }//邻接表基操
while (heap.size()) { auto t = heap.top(); heap.pop();
int ver = t.second, distance = t.first; if (st[ver]) continue;//确定最短边直接过 st[ver] = true; for (int i = h[ver]; i != -1; i = ne[i]) { int j = e[i]; if (dist[j] > distance + w[i]) { dist[j] = distance + w[i]; heap.push({dist[j], j});//入堆 } } }
if (dist[n] == 0x3f3f3f3f) // 走不通 return-1; return dist[n]; }
signedmain() { cin >> n >> m; memset(h, -1, sizeof h); while (m--) { int a, b, c; cin >> a >> b >> c; add(a, b, c); // 建边 } int t = dijkstra(); printf("%d", t); }
cin >> n >> m >> k; for (int i = 0; i < m; i++) { int a, b, w; cin >> a >> b >> w; edge[i] = {a, b, w}; } int t = bellman(); if (t > 0x3f3f3f3f / 2) puts("impossible"); else cout << t << endl; }
#include<bits/stdc++.h> usingnamespace std; typedef pair<int, int> PII; constint N = 1e6 + 10; int n, m; int e[N], w[N], h[N], ne[N], idx; int dist[N]; bool st[N];
voidadd(int a, int b, int c) { e[idx] = b; w[idx] = c; ne[idx] = h[a]; h[a] = idx++; }
while (q.size()) { int t = q.front(); q.pop(); st[t] = false;
for (int i = h[t]; i != -1; i = ne[i]) { int j = e[i]; if (dist[j] > dist[t] + w[i]) { dist[j] = dist[t] + w[i]; if (!st[j]) { q.push(j); st[j] = true; } } } }
return dist[n]; }
signedmain() { cin >> n >> m; memset(h, -1, sizeof h); while (m--) { int a, b, c; cin >> a >> b >> c; add(a, b, c); // 建边 } int t = spfa(); if (t == 0x3f3f3f3f) puts("impossible"); else cout << t << endl; }
#include<bits/stdc++.h> usingnamespace std; constint N = 210, INF = 1e9; #define int long long int n, m, q; int d[N][N]; voidfloyd() { for (int k = 1; k <= n; k++) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) d[i][j] = min(d[i][j], d[i][k] + d[k][j]); } } } signedmain() { ios::sync_with_stdio(false); cin.tie(nullptr); cin >> n >> m >> q; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (i == j) d[i][j] = 0; else d[i][j] = INF; } } while (m--) { int a, b, w; cin >> a >> b >> w; d[a][b] = min(d[a][b], w); } floyd(); while (q--) { int a, b; cin >> a >> b; if (d[a][b] > INF / 2) cout<<"impossible"<<endl; else cout << d[a][b] << endl; } }