具体思路和一些细节证明,周报里写的就挺不错的
一些个人理解补充在注释里:
#include<bits/stdc++.h>
#include<unordered_set>
#include<unordered_map>
#define mem(a,b) memset(a,b,sizeof a)
#define cinios (ios::sync_with_stdio(false),cin.tie(0),cout.tie(0))
#define cout_double(a) cout << setiosflags(ios::fixed) << setprecision(a)
#define sca scanf
#define pri printf
#define ul u << 1
#define ur u << 1 | 1
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const int N = 3010, M = 6010;
int INF = 0x3f3f3f3f, mod = 1e9 + 7;
ll LNF = 0x3f3f3f3f3f3f3f3f;
int n, m, k, T, S;
int h[N], e[M], ne[M], w[M], idx;
int dist[N], ds[N];
bool st[N];
int q[N], cnt[N];
struct edge
{
int a, b, w;
}eg[M];
ll ans[N];
void add(int a, int b, int x) {
e[idx] = b, ne[idx] = h[a], w[idx] = x, h[a] = idx++;
}
bool spfa() {
int hh = 0, tt = 0;
for (int i = 1; i <= n; i++)
q[tt++] = i, st[i] = true;
while (hh != tt)
{
int t = q[hh++];
if (hh == N)hh = 0;
st[t] = false;
for (int i = h[t]; ~i; i = ne[i]) {
int j = e[i];
if (ds[j] > ds[t] + w[i]) {
ds[j] = ds[t] + w[i];
cnt[j] = cnt[t] + 1;
if (cnt[j] > n)return true;
if (!st[j]) {
st[j] = true;
q[tt++] = j;
if (tt == N)tt = 0;
}
}
}
}
return false;
}
void dj(int s) {
mem(st, 0);
mem(dist, 0x3f);
dist[s] = 0;
priority_queue<PII, vector<PII>, greater<PII>> q;
q.push({ 0,s });
while (q.size())
{
PII t = q.top();
q.pop();
int ver = t.second;
if (st[ver])continue;
st[ver] = true;
for (int i = h[ver]; ~i; i = ne[i]) {
int j = e[i];
if (dist[j] > dist[ver] + w[i]) {
dist[j] = dist[ver] + w[i];
q.push({ dist[j],j });
}
}
}
}
int main() {
sca("%d%d", &n, &m);
mem(h, -1);
for (int i = 0; i < m; i++)
{
int a, b, x;
sca("%d%d%d", &a, &b, &x);
eg[i] = { a,b,x };
add(a, b, x);
}
if (spfa())cout << -1;
else {
mem(h, -1);
idx = 0;
for (int i = 0; i < m; i++) {
int a = eg[i].a, b = eg[i].b;
add(a, b, eg[i].w + ds[a] - ds[b]);
}
for (int i = 1; i <= n; i++) {
dj(i);
for (int j = 1; j <= n; j++) {
if (dist[j] == INF)dist[j] = 1e9;
else dist[j] = dist[j] - ds[i] + ds[j];
if (i == j)continue;
ans[i] += (ll)j * dist[j];
}
}
for (int i = 1; i <= n; i++)
pri("%lld\n", ans[i]);
}
return 0;
}