SPFA判断负环+链式前向星
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<map>
#include<cmath>
#include<cstdio>
#include<queue>
typedef long long ll;
const int mod = 1e9+7;
const int maxn = 1000000;
const int inf = 0x3f3f3f3f;
using namespace std;
/*SPFA判断是否存在负环*/
struct node
{
int u,v,w,next;
}e[10050];
int dis[10050],head[10050],cnt;
bool vis[10050];
int num[10050];//记录入队次数
int n,m,w;
void add(int u,int v,int w)
{
e[cnt].u = u;
e[cnt].v = v;
e[cnt].w = w;
e[cnt].next = head[u];
head[u] = cnt++;
}
bool spfa()
{
memset(vis,0,sizeof(vis));
memset(num,0,sizeof(num));
memset(dis,inf,sizeof(dis));
queue<int> q;
dis[1]=0;
q.push(1);
num[1]++;
while(!q.empty())
{
int x = q.front();
q.pop();
vis[x]=0;
for(int i = head[x];~i;i=e[i].next)
{
int v = e[i].v;
if(dis[v] > dis[x]+e[i].w)
{
dis[v] = dis[x] + e[i].w;
if(!vis[v])
{
vis[v]=1;
num[v]++;
q.push(v);
if( num[v]>=n )
{
return true;
}
}
}
}
}
return false;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int t;
cin>>t;
while(t--)
{
cnt = 0;
memset(head,-1,sizeof(head));
scanf("%d %d %d",&n,&m,&w);
for(int i=0;i<m;i++)
{
int u,v,s;
cin>>u>>v>>s;
add(u,v,s);
add(v,u,s);
}
for(int i=0;i<w;i++)
{
int u,v,s;
cin>>u>>v>>s;
add(u,v,-s);
}
if(spfa())
{
cout<<"YES"<<endl;
}
else
{
cout<<"NO"<<endl;
}
}
}