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
思路:最短路径,负数处理,判断cost[i][i]<0即可.
注意点:时间超时,Floyd()处理最小值时争取时间,代码还可以再改进.
#include<cstring>
#include<iostream>
#define min(a,b) a>b?b:a
//(Floyd-Wrashall算法)(求任意两点之间的最小距离)
const int MAX=501,INF=0x3f3f3f3f;
int cost[MAX][MAX];//cost[i][j]表示顶点i到顶点j的权值
int d[MAX];//顶点s出发的最短路径
bool used[MAX];//已经访问过的点
int V;//顶点数
using namespace std;
int floyd(){
for(int k=1;k<=V;k++) {
for (int i=1;i<=V;i++) {
for (int j=1;j<=V;j++){
/*int t=cost[i][k] + cost[k][j];
if(cost[i][j]>t)
cost[i][j]=t;
*///上面注释部分代码正确,但是时间1892ms,很危险!
cost[i][j]=min(cost[i][j],cost[i][k]+cost[k][j]);
}//参考别人的代码,为什么用min就会超时!!!
if(cost[i][i]<0)//能够遇到自己的条件
return 1;
}
}
return 0;
}
int main(){
int t,n,m,w,s,e,f;
cin>>t;
while(t--){
cin>>n>>m>>w;
memset(cost,INF,sizeof(cost));
memset(d,0,sizeof(d));
for(int i=0;i<=n;i++)
cost[i][i]=0;
for(int i=0;i<m;i++){
cin>>s>>e>>f;
cost[s][e]=cost[e][s]=min(f,cost[s][e]);
}
for(int i=0;i<w;i++){
cin>>s>>e>>f;
cost[s][e]=-f;//注意此处是单向的
}
V=n;
if(floyd())
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
}
/*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*/