POJ 3259 Wormholes(Bellman-Ford)

时间:2023-03-09 02:05:48
POJ 3259 Wormholes(Bellman-Ford)

http://poj.org/problem?id=3259

题意:
有一些普通的洞和虫洞,每个洞都有经过的时间,虫洞的时间是负的,也就是时光倒流,问是否能回到出发时的时间。

思路:

贝尔曼-福特算法判断负环。

 #include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
#include<set>
#include<map>
using namespace std; const int maxn = + ;
const int INF = + ; int n, num1, num2;
int cnt;
int d[maxn]; struct node
{
int s;
int e;
int w;
}g[maxn]; bool bellman()
{
memset(d, INF, sizeof(d));
for (int i = ; i < n; i++)
{
bool flag = false;
for (int j = ; j < cnt; j++)
{
if (d[g[j].e]>d[g[j].s] + g[j].w)
{
d[g[j].e] = d[g[j].s] + g[j].w;
flag = true;
}
}
if (!flag) break;
}
for (int j = ; j < cnt;j++)
if (d[g[j].e]>d[g[j].s] + g[j].w)
return true;
return false;
} int main()
{
//freopen("D:\\txt.txt", "r", stdin);
int T;
int a, b, t;
scanf("%d", &T);
while (T--)
{
cnt = ;
scanf("%d%d%d", &n, &num1, &num2);
for (int i = ; i < num1; i++)
{
scanf("%d%d%d", &a, &b, &t);
g[cnt].s = g[cnt + ].e = a;
g[cnt].e = g[cnt + ].s = b;
g[cnt].w = g[cnt + ].w = t;
cnt += ;
}
for (int i = ; i < num2; i++)
{
scanf("%d%d%d", &a, &b, &t);
g[cnt].s = a;
g[cnt].e = b;
g[cnt].w = -t;
cnt++;
}
if (bellman())
printf("YES\n");
else
printf("NO\n");
}
return ;
}