http://poj.org/problem?id=3259
Description
While exploring his many farms, Farmer John has discovered a number of amazing wormholes. A wormhole is very peculiar because it is a one-way path that delivers you to its destination at a time that is BEFORE you entered the wormhole! Each of FJ's farms comprises N (1 ≤ N ≤ 500) fields conveniently numbered 1..N, M (1 ≤ M ≤ 2500) paths, and W (1 ≤ W ≤ 200) wormholes.
As FJ is an avid time-traveling fan, he wants to do the following: start at some field, travel through some paths and wormholes, and return to the starting field a time before his initial departure. Perhaps he will be able to meet himself :) .
To help FJ find out whether this is possible or not, he will supply you with complete maps to F (1 ≤ F ≤ 5) of his farms. No paths will take longer than 10,000 seconds to travel and no wormhole can bring FJ back in time by more than 10,000 seconds.
Input
Line 1: A single integer, F. F farm descriptions follow.
Line 1 of each farm: Three space-separated integers respectively: N, M, and W
Lines 2..M+1 of each farm: Three space-separated numbers (S, E, T) that describe, respectively: a bidirectional path between S and E that requires T seconds to traverse. Two fields might be connected by more than one path.
Lines M+2..M+W+1 of each farm: Three space-separated numbers (S, E, T) that describe, respectively: A one way path from S to E that also moves the traveler back T seconds.
Output
Lines 1..F: For each farm, output "YES" if FJ can achieve his goal, otherwise output "NO" (do not include the quotes).
Sample Input
2
3 3 1
1 2 2
1 3 4
2 3 1
3 1 3
3 2 1
1 2 3
2 3 4
3 1 8
Sample Output
NO
YES
YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
#include<stdio.h>
#include<string.h>
#define NN 5500
#define inf 0x7fffffff
int m,n;
struct node
{
int star,end,time;
}map[NN];
__int64 dis[550],flag;//dis[i]表示从1到i的最短距离;为什么用__int64,因为0xfffffff是整形的最大值,计算加法时有可能溢出;
int bellman()
{
int i,j,k;
for(i=2;i<=n;i++)
dis[i]=inf;
dis[1]=0;自己到自己的距离为0;
for(i=1;i<n;i++)
{
flag=1;
for(j=1;j<m;j++)
{
int u=map[j].star;
int v=map[j].end;
int w=map[j].time;
if(dis[v]>dis[u]+w)
{
flag=0;
dis[v]=dis[u]+w;
//printf("dis[%d]>dis[%d]+%d\n",v,u,w);
}
}
if(flag)
break;
}
//printf("\n\n");
//flag=1;
/*for(i=1;i<m;i++)
printf("%d %d %d\n",map[i].star,map[i].end,map[i].time);*/
for(i=1;i<m;i++)
{
int u=map[i].star;
int v=map[i].end;
int w=map[i].time;
if(dis[v]>dis[u]+w)
{
//printf("dis[%d]>dis[%d]+%d\n",v,u,w);
return 1;
}
}
return 0;
}
int main()
{
int i,j,k,ncase,c,b,s,e,t;
scanf("%d",&ncase);
while(ncase--)
{
m=1;
scanf("%d%d%d",&n,&b,&c);
while(b--)
{
scanf("%d %d %d",&s,&e,&t);
map[m].star=s;
map[m].end=e;
map[m].time=t;
m++;
map[m].star=e;
map[m].end=s;
map[m].time=t;
m++;
}
while(c--)
{
scanf("%d %d %d",&s,&e,&t);
map[m].star=s;
map[m].end=e;
map[m].time=-t;
m++;
}
//printf("\n");
/*for(i=1;i<m;i++)
printf("%d %d %d\n",map[i].star,map[i].end,map[i].time);*/
if(!bellman())
printf("NO\n");
else
printf("YES\n");
}
return 0;
}