相當於找負環,因為 FJ 可以 start at some field,所以只要圖中存在負環,答案就是 YES
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
struct Edge {
int from, to, cost;
};
int V, E;
Edge edges[2500 * 2 + 200];
int d[500];
bool solve() {
// bellman ford : find negative cycle
memset(d, 0, sizeof(d)); // FJ can start at any vertex
d[0] = 0;
for (int i = 0; i < V; i++) {
for (int j = 0; j < E; j++) {
Edge& e = edges[j];
if (d[e.to] > d[e.from] + e.cost) {
d[e.to] = d[e.from] + e.cost;
if (i == V-1)
return true;
}
}
}
return false;
}
int main() {
int T;
scanf("%d", &T);
while (T--) {
int N, M, W;
scanf("%d %d %d", &N, &M, &W);
int idx = 0;
for (int i = 0; i < M; i++) {
int a, b, w;
scanf("%d %d %d", &a, &b, &w);
a--; b--;
edges[idx++] = Edge{a, b, w};
edges[idx++] = Edge{b, a, w};
}
for (int i = 0; i < W; i++) {
int a, b, w;
scanf("%d %d %d", &a, &b, &w);
a--; b--;
edges[idx++] = Edge{a, b, -w};
}
V = N;
E = idx;
if (solve())
puts("YES");
else
puts("NO");
}
return 0;
}