Wormholes
Wormholes
spfa 判负环
SCUACM2022集训前训练-图论 - Virtual Judge (vjudge.net)
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>
#include <queue>
using namespace std;
typedef long long ll;
const int N = 5e2 + 10;
struct Edge
{
int to, val;
};
vector<vector<Edge> > G(N);
int n, m, q;
bool st[N];
int dist[N], cnt[N];
void init()
{
memset(cnt, 0, sizeof cnt);
memset(dist, 0, sizeof dist);
memset(st, false, sizeof st);
for (int i = 0; i < N; i++)
G[i].clear();
}
void add(int u, int v, int w)
{
G[u].push_back({v, w});
}
bool spfa()
{
queue<int> q;
for (int i = 1; i <= n; i++)
{
q.push(i);
st[i] = true;
}
while(!q.empty())
{
int u = q.front();
q.pop();
st[u] = false;
for (int i = 0; i < G[u].size(); i++)
{
int v = G[u][i].to, w = G[u][i].val;
if (dist[v] > dist[u] + w)
{
dist[v] = dist[u] + w;
cnt[v] = cnt[u] + 1;
if (cnt[v] >= n)
return true;
if (!st[v])
{
q.push(v);
st[v] = true;
}
}
}
}
return false;
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int T;
cin >> T;
while(T--)
{
cin >> n >> m >> q;
init();
for (int i = 1; i <= m; i++)
{
int u, v, w;
cin >> u >> v >> w;
add(u, v, w), add(v, u, w);
}
for (int i = 1; i <= q; i++)
{
int u, v, w;
cin >> u >> v >> w;
add(u, v, -w);
}
if (spfa())
cout << "YES" << endl;
else
cout << "NO" << endl;
}
return 0;
}