- 题目大意
个人要穿越到未来,但是之后还要回去,并且回去的时间要在他穿越之前。
- 解题思路
我们可以把在虫洞中的时间看做是负边权,然后利用bellman-ford算法来判断有没有负环即可。
- 代码
#include<cstdio>
#include<cstring>
using namespace std;
const int M=1e5;
const int INF=0x3f3f3f;
int d[M],cnt;
struct edge{
int u,v,w;
}e[M];
bool BellmanFord(int s,int n,int m)
{
memset(d,INF,sizeof(d));
d[s]=0;
bool updated=true;
int round =0;
while(updated)
{
updated=false;
round++;
for(int i=0;i<m;i++)
{
int u=e[i].u,v=e[i].v,w=e[i].w;
if(d[v]>d[u]+w)
{
d[v]=d[u]+w;
updated=true;
}
}
if(round>=n&&updated)
return true;
}
return false;
}
int main()
{
int t,n,m,w,k,s,time;
scanf("%d",&t);
while(t--)
{
scanf("%d%d%d",&n,&m,&w);
cnt=0;
for(int i=0;i<m;i++)
{
scanf("%d%d%d",&s,&k,&time);
e[cnt].u=s;
e[cnt].v=k;
e[cnt++].w=time;
e[cnt].u=k;
e[cnt].v=s;
e[cnt++].w=time;
}
for(int i=0;i<w;i++)
{
scanf("%d%d%d",&s,&k,&time);
e[cnt].u=s;
e[cnt].v=k;
e[cnt++].w=-time;
}
if(BellmanFord(1,n,cnt))
printf("%s\n","YES");
else
printf("%s\n","NO");
}
}