SPFA算法中当某个顶点进入队列次数大于等于n的时候就说明存在负权回路了。
恩就是这样。。。。
#pragma warning(disable:4996) #include <cstdio> #include <cstring> #include <vector> #include <queue> #include <algorithm> using namespace std; const int N = 505; vector<int>g[N], e[N]; int cnt[N], dis[N]; bool in[N]; int n, m, w; void add(int u, int v, int c) { g[u].push_back(v); e[u].push_back(c); } bool spfa() { memset(in, false, sizeof in); memset(dis, 0x3f, sizeof dis); memset(cnt, 0, sizeof cnt);//入队次数 queue<int>q; q.push(1); dis[1] = 0; in[1] = true; while (!q.empty()) { int u = q.front(); q.pop(); in[u] = false; for (int i = 0; i < (int)g[u].size(); i++) { int v = g[u][i], c = e[u][i]; if (dis[v] > dis[u] + c) { dis[v] = dis[u] + c; if (!in[v]) { q.push(v); in[v] = true; cnt[v]++; if (cnt[v] == n)return true; } } } } return false; } int main() { //freopen("in.txt", "r", stdin); int t; scanf("%d", &t); while (t--) { scanf("%d %d %d", &n, &m, &w); for (int i = 1; i <= n; i++) { g[i].clear(); e[i].clear(); } for (int i = 1; i <= m; i++) { int u, v, c; scanf("%d %d %d", &u, &v, &c); add(u, v, c); add(v, u, c); } for (int i = 1; i <= w; i++) { int u, v, c; scanf("%d %d %d", &u, &v, &c); add(u, v, -c); } if (spfa())puts("YES"); else puts("NO"); } return 0; }