对于 $x_i - x_j \leq c \to x_i \leq x_j + c$,建单向边 $(j,i,c)$。
对于 $x_i - x_j \geq c \to x_j \leq x_i - c$,建单向边 $(i,j,-c)$。
然后跑 spfa 判断负环,顺便求解。
#include <bits/stdc++.h>
using namespace std;
const int N = 5e3 + 15, M = N << 1;
int n, m;
int h[N], e[M], w[M], ne[M], idx = 0;
void add(int a, int b, int c) {
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
int dist[N], cnt[N];
bool st[N];
bool spfa() {
for (int i = 0; i <= n; i++) dist[i] = 0x3f3f3f3f, cnt[i] = 0, st[i] = 0;
st[0] = 1, dist[0] = 0, cnt[0] = 1;
queue<int> q; q.push(0);
while (q.size()) {
int u = q.front(); q.pop();
st[u] = 0;
for (int i = h[u]; ~i; i = ne[i]) {
int v = e[i];
if (dist[v] > dist[u] + w[i]) {
dist[v] = dist[u] + w[i];
cnt[v] = cnt[u] + 1;
if (cnt[v] > n + 1) return 1;
if (!st[v]) q.push(v), st[v] = 1;
}
}
}
return 0;
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i <= n; i++) h[i] = -1;
for (int i = 1; i <= n; i++) add(0, i, 0);
while (m--) {
int x, y, c; scanf("%d%d%d", &x, &y, &c);
add(y, x, c);
}
if (spfa()) puts("NO");
else
for (int i = 1; i <= n; i++) printf("%d ", dist[i]);
return 0;
}