题目链接:
https://begin.lydsy.com/JudgeOnline/problem.php?id=1668
Description:
John在他的农场中发现了许多虫洞。虫洞可以看作一条有向边,可以使你回到过去的时刻(相对你进入虫洞之前)。John的每个农场有M条小路(无向边)连接着N(从1…N标号)块地,有W个虫洞
现在John想借助这些虫洞来回到过去(出发时刻之前),请你告诉他能办到吗。
Sample Input:
2//2组数据
3 3 1//3个点,3条无向边,1条有向边(负权边)
1 2 2
1 3 4
2 3 1
3 1 3
3 2 1//3个点,2条无向边,1条有向边(负权边)
1 2 3
2 3 4
3 1 8
Sample Output:
NO
YES
解题思路:
本题是求是否在农场中存在一个负环
一个需要注意的地方:
存储边的数量为2500*2(双向边)+200(单向边)=5200条
代码:
#include<bits/stdc++.h>
using namespace std;
struct Node{
int B,E,dis;
}edge[5202];//存储边的结构体
int T,n,m,w,cnt,d[5202];
inline bool Judge(){
for(int i=2;i<=n;i++)
d[i]=123456789;
d[1]=0;
//SPFA最短路算法判断负环
for(int i=1;i<=n;i++)
for(int j=1;j<=cnt;j++)
if(d[edge[j].E]>d[edge[j].B]+edge[j].dis){//成功回到过去
d[edge[j].E]=d[edge[j].B]+edge[j].dis;
if(i==n)//成功走完整个农场并回到过去
return 1;
}
return 0;
}
int main(){
scanf("%d",&T);//T个农场
while(T--){
scanf("%d%d%d",&n,&m,&w);
cnt=0;
for(int i=1,s,e,t;i<=m;i++){
scanf("%d%d%d",&s,&e,&t);
edge[++cnt].B=s,edge[cnt].E=e,edge[cnt].dis=t;//连一条从s到e,边权为t的边
edge[++cnt].B=e,edge[cnt].E=s,edge[cnt].dis=t;//路是双向边
}
for(int i=1,s,e,t;i<=w;i++){
scanf("%d%d%d",&s,&e,&t);
edge[++cnt].B=s,edge[cnt].E=e,edge[cnt].dis=-t;//虫洞可以回到过去,而不能去到未来,所以这是一条边权为-t的单向边
}
if(Judge())//成功
printf("YES\n");
else
printf("NO\n");
}
}