【集训整理】差分约束 模板题
#include<iostream>
#include<queue>
#include<cstring>
#define N 51000
using namespace std;
int v[N], w[N], nex[N];
int d[N], cnt[N], first[N];
bool vis[N]; int t;
int n,m;
void add(int x, int y, int z){
t++;
nex[t] = first[x];
first[x] = t;
v[t] = y;
w[t] = z;
}
bool SPFA(int s){
int x, y, i, j;
queue<int>q;
memset(d, 0x3f, sizeof(d));
memset(vis, false, sizeof(vis));
while (!q.empty()) q.pop();
d[s] = 0;
cnt[s] = 1;
q.push(s);
vis[s] = true;
while (!q.empty()){
x = q.front();
q.pop();
vis[x] = false;
for (i = first[x]; i; i = nex[i]){
y = v[i];
if (d[y] > d[x] + w[i]){
d[y] = d[x] + w[i];
cnt[y] = cnt[x] + 1;
if (cnt[y] > n)
return false;
if (!vis[y]){
q.push(y);
vis[y] = true;
}
}
}
}
return true;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= m; i++) {
int a, b, c;
cin >> b >> a >> c;
add(a, b, c);
}
d[n + 1] = 0;
for (int i = 1; i <= n; i++) add(n + 1, i,0);
if (SPFA(n+1))
cout << "YES";
else
cout << "NO";
}最后更新于