POJ - 3259 - Wormholes(floyd求负环)
题目链接
题目大意:给你一个加权图,里面有m个无向正权边和w个单向负边,判断有没有负环。
floyd可以求两点之间的最短路,如果两个点一样,即是一个环,判断图中环的大小是不是负即可。
const int maxn = 1e3+10;
int g[maxn][maxn], n, m, w;
void init() {
for (int i = 0; i<=n; ++i)
for (int j = 0; j<=n; ++j)
g[i][j] = i==j? 998244353:INF;
}
bool flyod() {
for (int i = 1; i<=n; ++i)
for (int j = 1; j<=n; ++j)
if (g[j][i]!=INF)
for (int k =1; k<=n; ++k)
if (g[j][k] > g[j][i] + g[i][k])
g[j][k] = g[j][i] + g[i][k];
for (int i = 1; i<=n; ++i)
if (g[i][i]<0) return true;
return false;
}
int main(void) {
int t;
scanf("%d", &t);
while(t--) {
scanf("%d%d%d", &n, &m, &w);
init();
for (int i = 0, u, v, c; i<m; ++i) {
scanf("%d%d%d", &u, &v, &c);
if (g[u][v] > c) g[u][v] = g[v][u] = c;
}
for (int i = 0, u, v, c; i<w; ++i) {
scanf("%d%d%d", &u, &v, &c);
if (g[u][v] > -c) g[u][v] = -c;
}
printf(flyod() ? "YES\n" : "NO\n");
}
return 0;
}