差分约束问题(判定负环)
#include<iostream> #include<cstring> #include<cstdio> #include<algorithm> #include<queue> using namespace std; const int INF = 1e9; const int maxn = 300; struct Node { int p; int next; int len; }G[5000]; int z = 0; int head[maxn]; void add(int be, int en, int len) { G[++z].p = en; G[z].len = len; G[z].next = head[be]; head[be] = z; } int n, m; int vis[maxn]; int cnt[maxn]; int dis[maxn]; int gi() { int a = 0; char x = getchar(); bool f = 0; while ((x<'0' || x>'9') && x != '-')x = getchar(); if (x == '-')x = getchar(), f = 1; while (x >= '0'&&x <= '9')a = (a << 3) + (a << 1) + x - 48, x = getchar(); return f ? -a : a; } int spfa(int be) { queue<int>que; for (int i = 0; i <= n; i++) dis[i] = INF; dis[be] = 0; vis[be] = 1; que.push(be); while (que.size()) { int x = que.front(); que.pop(); vis[x] = 0; ++cnt[x]; if (cnt[x] == n) return 0;//有错 for (int i = head[x]; i; i = G[i].next) { int p = G[i].p; if (dis[p] > dis[x] + G[i].len) { dis[p] = dis[x] + G[i].len; if (!vis[p] ) { que.push(p); vis[p] = 1; } } } } return 1; } int main() { int t; t = gi(); while (t--) { n = gi(); m = gi(); int be, en, len; memset(head, 0, sizeof(head)); z = 0; memset(vis, 0, sizeof(vis)); memset(cnt, 0, sizeof(cnt)); for (int i = 0; i < m; i++) { be = gi(); en = gi(); len = gi(); add(be - 1, en, len); add(en, be - 1, -len); } int flag = 0; for (int i = 0; i <= n; i++) { if (!cnt[i] ) { if (!spfa(i)) { flag = 1; break; } } } if (!flag) printf("true "); else printf("false "); } return 0; }