题目链接:3259 -- Wormholes
样例输入:
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
样例输出:
NO
YES
简化题意:有n个点,m条双向边,双向边权值为正,还有w条单向边,权值为负,问能否找到一个负环。
这就是一个基本的spfa判负环问题,不会spfa的小伙伴可以看下这里:spfa判断负环_AC__dream的博客-CSDN博客_spfa判断负环
下面是代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
const int N=1e6+10;
int h[N],e[N],w[N],ne[N],idx,dist[N],cnt[N];
bool vis[N];
int n,m1,m2;
void add(int x,int y,int z)
{
e[idx]=y;
w[idx]=z;
ne[idx]=h[x];
h[x]=idx++;
}
bool spfa()
{
queue<int>q;
for(int i=1;i<=n;i++)//由于负环不一定是到源点的路径上产生的,所以要把所有点入队列
{
q.push(i);
vis[i]=true;
}
while(!q.empty())
{
int t=q.front();
q.pop();
vis[t]=false;
for(int i=h[t];i!=-1;i=ne[i])
{
int j=e[i];
if(dist[j]>dist[t]+w[i])
{
dist[j]=dist[t]+w[i];
cnt[j]=cnt[t]+1;
if(cnt[j]>=n)
{
// cout<<"**"<<j<<"**"<<endl;
return true;
}
if(!vis[j])
{
q.push(j);
vis[j]=true;
}
}
}
}
return false;
}
int main()
{
int T;
cin>>T;
while(T--)
{
scanf("%d%d%d",&n,&m1,&m2);
idx=0;
for(int i=1;i<=n;i++)
h[i]=-1,cnt[i]=0,dist[i]=0x3f3f3f3f;
int u,v,t;
for(int i=1;i<=m1;i++)
{
scanf("%d%d%d",&u,&v,&t);
add(u,v,t);add(v,u,t);
}
for(int i=1;i<=m2;i++)
{
scanf("%d%d%d",&u,&v,&t);
add(u,v,-t);
}
if(spfa()) puts("YES");
else puts("NO");
}
return 0;
}