Luogu P5960 【模板】差分约束算法

题目描述

https://www.luogu.com.cn/problem/P5960

Solution

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
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#define maxn 5010
#define maxm 5010
using namespace std;

int n, m, s;

struct Edge {
int to, next, w;
} e[maxn + maxm]; int c1, head[maxn];
inline void add_edge(int u, int v, int w) {
e[c1].to = v; e[c1].w = w;
e[c1].next = head[u]; head[u] = c1++;
}

int dis[maxn], cnt[maxn]; bool vis[maxn]; queue<int> Q;
bool spfa(int s) {
memset(dis, 10, sizeof dis); dis[s] = 0;
memset(cnt, 0, sizeof cnt);
memset(vis, 0, sizeof vis); Q.push(s);
while (!Q.empty()) {
int u = Q.front(); Q.pop(); vis[u] = 0;
if (cnt[u] >= n + 1) return 1;
for (int i = head[u]; ~i; i = e[i].next) {
int v = e[i].to, w = e[i].w;
if (dis[v] > dis[u] + w) {
dis[v] = dis[u] + w;
cnt[v] = cnt[u] + 1;
if (vis[v]) continue; vis[v] = 1;
Q.push(v);
}
}
} return 0;
}

int main() { memset(head, -1, sizeof head);
ios::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);

cin >> n >> m; s = 0;
for (int i = 1; i <= m; ++i) {
int x, y, z; cin >> x >> y >> z;
add_edge(y, x, z);
}
for (int i = 1; i <= n; ++i) add_edge(s, i, 0);
if (spfa(s)) return cout << "NO" << "\n", 0;
for (int i = 1; i <= n; ++i) cout << dis[i] << " "; cout << "\n";
return 0;
}