poj3259 Wormholes
题意:首先输入三个量 N个fields、M个paths、W个wormholes。然后是M行,指 a 和 b 之间的无向边所需花 c 秒。然后是W行,指 a 到 b 所需 -c 秒(这个是有向边)。问你是否存在环?
解决方法:经典的判断负环的题。我用的是Bellman - Ford 算法,就是进行 n - 1 次松弛操作,若进行后仍可以进行松弛操作,就代表有负环,否则负环不存在。
代码实现:
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <string>
#include <cstring>
#include <cstdio>
#include <vector>
#define Inf 6000000
using namespace std;
struct node
{
int from;
int to;
int dis;
}v[10000];
bool vis[550];
int few[550];
int spfa(int x, int n)
{
int flag = 0;
for(int i = 0; i < n-1; i++)
{
for(int j = 0; j < x; j++)
{
if(few[v[j].to] > few[v[j].from] + v[j].dis)
{
few[v[j].to] = few[v[j].from] + v[j].dis;
flag = 1;
}
}
if(!flag) break;
}
for(int i = 0; i < x; i++)
if(few[v[i].to] > few[v[i].from] + v[i].dis)
return 0;
return 1;
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
int n, m, w;
scanf("%d%d%d", &n, &m, &w);
int cnt = 0;
for(int i = 0; i < n; i++)
few[i] = Inf;
for(int i = 0; i < m; i++)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
v[cnt].from = a;
v[cnt].to = b;
v[cnt++].dis = c;
v[cnt].from = b;
v[cnt].to = a;
v[cnt++].dis = c;
}
for(int i = 0; i < w; i++)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
v[cnt].from = a;
v[cnt].to = b;
v[cnt++].dis = -c;
}
memset(vis, false, sizeof(vis));
few[0] = 0;
int ans = spfa(cnt, n);
if(!ans) printf("YES\n");
else printf("NO\n");
}
return 0;
}
若有错,请大家多多指教^ ^