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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| #include<bits/stdc++.h> using namespace std; #define pll pair<int,int> #define int long long const int inf = 1e9; int n,m; struct{ int v, w, next; } a[10010]; int head[5010],dis[5010],h[5010],cnt[5010]; bool vis[5010]; int edge; void add(int u,int v,int w) { a[++edge].v = v; a[edge].w = w; a[edge].next = head[u]; head[u] = edge; } bool spfa() { memset(h, 0x3f, sizeof h); queue<int> q; h[0] = 0; vis[0] = 1; q.push(0); while(q.size()) { int u = q.front(); q.pop(); vis[u] = 0; for (int i = head[u]; i;i=a[i].next) { int v = a[i].v, w = a[i].w; if(h[v]>h[u]+w) { h[v] = h[u] + w; if(!vis[v]) { vis[v] = true; q.push(v); cnt[v]++; if(cnt[v]>n) return false; } } } } return true; } void dijkstra(int s) { priority_queue<pll, vector<pll>, greater<pll>> q; for (int i = 1; i <= n;i++) dis[i] = inf; memset(vis, 0, sizeof vis); dis[s] = 0; q.push({0, s}); while(q.size()) { pll t = q.top(); q.pop(); int u = t.second; if(vis[u]) continue; vis[u] = true; for (int i = head[u]; i;i=a[i].next) { int v = a[i].v; if(dis[v]>dis[u]+a[i].w) { dis[v] = dis[u] + a[i].w; q.push({dis[v], v}); } } } } signed main() { ios::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); cin >> n >> m; while(m--) { int u, v, w; cin >> u >> v >> w; add(u, v, w); } for (int i = 1; i <= n;i++) add(0, i, 0); if(!spfa()) { cout << "-1" << endl; return 0; } for (int u = 1; u <= n;u++) for (int i = head[u]; i;i=a[i].next) a[i].w += h[u] - h[a[i].v]; for (int i = 1; i <= n;i++) { dijkstra(i); int ans = 0; for (int j = 1; j <= n;j++) { if(dis[j]==inf) ans += j * inf; else ans += j * (dis[j] + h[j] - h[i]); } cout << ans << endl; } }
|