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
| #include<bits/stdc++.h> using namespace std; #define int long long const int MAXn = 3e3; const int MAXm = 6e3; const int INF = 1e9;
template <typename T> inline void read(T &a) { char c;for (c = getchar(); (c < '0' || c > '9') && c != '-'; c = getchar());bool f = c == '-';T x = f ? 0 : (c ^ '0');for (c = getchar(); c >= '0' && c <= '9'; c = getchar()) {x = x * 10 + (c ^ '0');}a = f ? -x : x; } template <typename T, typename ...Argv> inline void read(T &a, Argv &...argv) { read(a), read(argv...); }
inline void clear(priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> &pq) { priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pqempty; pq = pqempty; }
int head[MAXn + 10], cntnex, nex[MAXm + MAXn + 10], from[MAXm + MAXn + 10], to[MAXm + MAXn + 10], wei[MAXm + MAXn + 10]; inline void Insert(int u, int v, int w) { nex[++cntnex] = head[u]; head[u] = cntnex; from[cntnex] = u; to[cntnex] = v; wei[cntnex] = w; }
int n, m; int h[MAXn + 10], cntinque[MAXn + 10]; bool inque[MAXn + 10]; queue<int> q; bool Spfa(int sour) { fill(begin(h), end(h), INF); h[sour] = 0; q.push(sour); inque[sour] = 1; ++cntinque[sour]; while (!q.empty()) { int cur = q.front(); q.pop(); inque[cur] = 0; for (int i = head[cur]; i; i = nex[i]) { if (h[to[i]] > h[cur] + wei[i]) { h[to[i]] = h[cur] + wei[i]; if (!inque[to[i]]) { q.push(to[i]); inque[to[i]] = 1; ++cntinque[to[i]]; if (cntinque[to[i]] > n + 1) { return 0; } } } } } return 1; } int dis[MAXn + 10]; bool vis[MAXn + 10]; priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq; void Dijkstra(int sour) { memset(vis, 0, sizeof(vis)); fill(begin(dis), end(dis), INF); dis[sour] = 0; pq.push(make_pair(0, sour)); while (!pq.empty()) { int cur = pq.top().second; pq.pop(); if (vis[cur]) continue; vis[cur] = 1; for (int i = head[cur]; i; i = nex[i]) { if (vis[to[i]]) continue; if (dis[to[i]] > dis[cur] + wei[i]) { dis[to[i]] = dis[cur] + wei[i]; pq.push(make_pair(dis[to[i]], to[i])); } } } } signed main() { read(n, m); for (int i = 1, u, v, w; i <= m; ++i) { read(u, v, w); Insert(u, v, w); } for (int i = 1; i <= n; ++i) { Insert(n + 1, i, 0); } if (!Spfa(n + 1)) { puts("-1"); return 0; } for (int i = 1; i <= cntnex; ++i) { wei[i] = wei[i] + h[from[i]] - h[to[i]]; } for (int i = 1; i <= n; ++i) { int ans = 0; Dijkstra(i); for (int j = 1; j <= n; ++j) { if (dis[j] == INF) { ans += j * INF; } else { ans += j * (dis[j] - h[i] + h[j]); } } printf("%lld\n", ans); } return 0; }
|