题目:
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 backT 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
题意:
昆虫洞
给你一个F,代表有F组测试数据。
第1行,3个数,N,M,W。
第2行到M+1行,每行3个数S,E,T,表示一条从S到E的双向路,通过这条路需要时间T,两块地之间至多有一条路。
第M+2到M+W+1行,每行3个数S,E,T,表示一条从S到E的单向路,通过这条路需要时间-T,即时间倒退T;
求从某块地出发,通过一些路和昆虫洞后还回原点,时间比他出发的时间早,使他能碰到出发前的他自己。
思路:
从题目就可以知道,这是一道最短路问题,而且还有负权边,所以应该用Bellman—Ford算法,同时还要判断是否存在负权边,判断方法在代码中讲。
代码如下:
#include<stdio.h>
#include<string.h>
#define inf 999999999
int t,n,m,k,s;
int a,b,c,flag;
int v[6001],u[6001],w[6001];
int dis[6001];
void init()//初始化;
{
for(int i=2; i<=n; i++)
dis[i]=inf;
return ;
}
void panduan()//判断是否存在负权边;
{
for(int i=1; i<=s; i++)
{
if(dis[v[i]]>dis[u[i]]+w[i])
flag=1;
}
return ;
}
void Bellman_ford()
{
int i,j;
init();
dis[1]=0;
flag=0;
for(i=1; i<=n; i++)
{
for(j=1; j<=s; j++)
{
if(dis[v[j]]>dis[u[j]]+w[j])
dis[v[j]]=dis[u[j]]+w[j];
}
}
panduan();//如果进行了N-1次的放缩后还能够放缩,那么就存在负权边;
if(flag==1)
printf("YES\n");
else
printf("NO\n");
return ;
}
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%d%d%d",&n,&m,&k);
int i,j;
s=1;
for(i=1; i<=m;i++)//注意是双向路;
{
scanf("%d%d%d",&a,&b,&c);
u[s]=a;
v[s]=b;
w[s++]=c;
v[s]=a;
u[s]=b;
w[s++]=c;
}
for(i=1; i<=k; i++)//注意是单向路;
{
scanf("%d%d%d",&a,&b,&c);
u[s]=a;
v[s]=b;
w[s++]=-c;
}
Bellman_ford();
}
return 0;
}