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
| #include <cstdio> #include <queue> using namespace std; typedef long long LL; typedef pair<int, int> PII; template <class Type> void read(Type &x) { char c; bool flag = false; while ((c = getchar()) < '0' || c > '9') c == '-' && (flag = true); x = c - '0'; while ((c = getchar()) >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0'; flag && (x = ~x + 1); } template <class Type> void write(Type x) { x < 0 && (putchar('-'), x = ~x + 1); x > 9 && (write(x / 10), 0); putchar(x % 10 + '0'); } const int N = 3e3 + 10, M = 1e4 + 10, inf = 1e9; bool vis[N]; int n, m, h[N], dis[N][N], cnt[N]; int idx, hd[N], nxt[M], edg[M], wt[M]; bool spfa(int st, int *d) { for (int i = 1; i <= n; i++) d[i] = inf; queue<int> q; q.push(st); vis[st] = true; while (!q.empty()) { int t = q.front(); q.pop(); vis[t] = false; for (int i = hd[t]; ~i; i = nxt[i]) if (d[t] + wt[i] < d[edg[i]]) { d[edg[i]] = d[t] + wt[i]; cnt[edg[i]] = cnt[t] + 1; if (cnt[edg[i]] > n) return false; if (!vis[edg[i]]) { vis[edg[i]] = true; q.push(edg[i]); } } } return true; } void dijkstra(int st, int *d) { for (int i = 1; i <= n; i++) { vis[i] = false; cnt[i] = 0; d[i] = inf; } priority_queue<PII, vector<PII>, greater<PII>> q; d[st] = 0; q.push(make_pair(0, st)); while (!q.empty()) { int t = q.top().second; q.pop(); if (vis[t]) continue; vis[t] = true; for (int i = hd[t]; ~i; i = nxt[i]) if (d[t] + wt[i] < d[edg[i]]) { d[edg[i]] = d[t] + wt[i]; q.push(make_pair(d[edg[i]], edg[i])); } } for (int i = 1; i <= n; i++) d[i] < inf && (d[i] += h[i] - h[st]); } void add(int a, int b, int c) { nxt[++idx] = hd[a]; hd[a] = idx; edg[idx] = b; wt[idx] = c; } int main() { read(n), read(m); for (int i = 0; i <= n; i++) hd[i] = -1; for (int u, v, w; m; m--) { read(u), read(v), read(w); add(u, v, w); } for (int i = 1; i <= n; i++) add(0, i, 0); if (!spfa(0, h)) return puts("-1"), 0; for (int i = 1; i <= n; i++) for (int j = hd[i]; ~j; j = nxt[j]) wt[j] += h[i] - h[edg[j]]; for (int i = 1; i <= n; i++) dijkstra(i, dis[i]); return 0; }
|