代码解释很清楚
#include<iostream>
#include<string>
#include<math.h>
#include<algorithm>
#include<vector>
#include<queue>
//#include<bits/stdc++.h>
typedef long long ll;
#define INF 0x3f3f3f3f
ll gcd(ll a, ll b)
{
return b ? gcd(b, a % b) : a;
}
ll lcm(ll a, ll b) {
return a * b / (gcd(a, b));
}
#define PII pair<int,int>
using namespace std;
const int N = 2e6 + 10, mod = 1e9 + 7;
int qmi(int a, int k, int p) //快速幂模板
{
int res = 1;
while (k)
{
if (k & 1) res = (ll)res * a % p;
k >>= 1;
a = (ll)a * a % p;
}
return res;
}
///
int n,m,w;
struct Edge
{
int v, w, next;
}edge[N];
int head[N], dis[N], vis[N], t;
void Init()
{
memset(head, -1, sizeof(head));
t = 0;
}
void Add_edge(int u, int v, int w)
{
edge[t].v = v; edge[t].w = w; edge[t].next = head[u]; head[u] = t++;
}
bool SPFA()
{
int mark[N];//记录每个点如队列的次数
for (int i = 1; i <= n; i++)
{
mark[i] = 0; dis[i] = INF; vis[i] = 0;
}
queue<int> q;
q.push(1); //我们只需要判断负环,随便找一个起点就好
dis[1] = 0;
vis[1] = 1;//入队列
mark[1] ++;
while (!q.empty())
{
int u = q.front();
q.pop();
vis[u] = 0;//出队列
for (int i = head[u]; i != -1; i = edge[i].next)
{
int v = edge[i].v;
if (dis[v] > dis[u] + edge[i].w)
{
dis[v] = dis[u] + edge[i].w;
if (!vis[v])//不在队列中的时候出队
{
q.push(v); mark[v] ++; vis[v] = 1;
}
if (mark[v] >= n)//如果不存在负环,那么最多更新n-1次就可以得到最终的答案,因为一次最少更新一个节点,那么如果出现了更新n次,那么就一定出现了负环
return false;
}
}
}
return true;
}
int main()
{
int t;
cin >> t;
while (t--)
{
Init();
int u, v, z;
cin >> n >> m >> w;
for (int i = 0; i < m; i++)
{
cin >> u >> v >> z;
Add_edge(u, v, z);
Add_edge(v, u, z);
}
for (int i = 0; i < w; i++)
{
cin >> u >> v >> z;
Add_edge(u, v, -z);
}
if (!SPFA())
cout << "YES" << endl;
else
cout << "NO" << endl;
}
return 0;
}