// Problem: P5905 【模板】全源最短路(Johnson) // Contest: Luogu // URL: https://www.luogu.com.cn/problem/P5905 // Memory Limit: 128 MB // Time Limit: 1000 ms // // Powered by CP Editor (https://cpeditor.org)
#include<bits/stdc++.h> usingnamespace std; typedeflonglong ll; typedefunsignedlonglong ull; #define int long long
constint N = 3e3 + 9; constint INF = 1e9;
int n, m, h[N], dis[N][N]; structEdge { int x, y, w; }; structNode { int x, w; booloperator < (const Node &u) const { return w == u.w ? x < u.x : w > u.w; } }; vector <Node> g[N]; vector <Edge> bg;
boolBellman_Ford() { for (int i = 1; i <= n; i++) h[i] = INF; for (int i = 1; i <= n; i++) { for (auto &m : bg) { if (h[m.x] == INF) continue; if (h[m.x] + m.w < h[m.y]) h[m.y] = h[m.x] + m.w; } } for (auto &m : bg) { if (h[m.x] == INF) continue; if (h[m.x] + m.w < h[m.y]) returnfalse; } returntrue; }
voiddijkstra(int st) { int d[N]; bitset <N> vis; for (int i = 1; i <= n; i++) d[i] = INF; priority_queue <Node> pq; d[st] = 0; pq.push({st, d[st]}); while (!pq.empty()) { int x = pq.top().x; pq.pop(); if (vis[x] == true) continue; vis[x] = true; for (auto &m : g[x]) { if (d[x] + m.w < d[m.x]) { d[m.x] = d[x] + m.w; pq.push({m.x, d[m.x]}); } } } for (int i = 1; i <= n; i++) dis[st][i] = d[i]; }
signedmain() { ios::sync_with_stdio(0), cin.tie(0), cout.tie(0); cin >> n >> m; for (int i = 1; i <= m; i++) { int u, v, w; cin >> u >> v >> w; g[u].push_back({v, w}); bg.push_back({u, v, w}); } for (int i = 1; i <= n; i++) bg.push_back({0, i, 0}); if (!Bellman_Ford()) { cout << -1 << '\n'; return0; } for (int i = 1; i <= n; i++) for (auto &y : g[i]) { y.w = y.w + h[i] - h[y.x]; // cout << y.w << ' '; } for (int i = 1; i <= n; i++) dijkstra(i); for (int i = 1; i <= n; i++) { int sum = 0; for (int j = 1; j <= n; j++) { if (dis[i][j] == INF) sum += 1ll * j * INF; else sum += 1ll * j * (dis[i][j] - h[i] + h[j]); } cout << sum << '\n'; } return0; }
igned main() { ios::sync_with_stdio(0), cin.tie(0), cout.tie(0); cin >> n >> m; for (int i = 1; i <= m; i++) // 存图 { int u, v, w; cin >> u >> v >> w; g[u].push_back({v, w}); bg.push_back({u, v, w}); } for (int i = 1; i <= n; i++) bg.push_back({0, i, 0}); // 将所有便与 0点 的距离存入图中 if (!Bellman_Ford()) // 如果有负环,则输出 -1,同时处理了权重 { cout << -1 << '\n'; return0; } for (int i = 1; i <= n; i++) // 将所有权重全部处理掉 for (auto &y : g[i]) y.w = y.w + h[i] - h[y.x];