题目链接:https://www.luogu.com.cn/problem/P3385
题解:Bellman_ford判负环,注意数据加强后,需要判断是否负环与点1相连,记录个tmp[]来记录是否有点与1相连。
#include<bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 1e4+10;
int dis[maxn], tmp[maxn];
int from[maxn], to[maxn], cost[maxn];
int n, m, cnt;
void solve()
{
cin >> n >> m;
cnt = 1;
for (int i = 1; i <= m; i++)
{
int a, b, c;
cin >> a >> b >> c;
from[cnt] = a;
to[cnt] = b;
cost[cnt] = c;
cnt++;
if (c >= 0)
{
from[cnt] = b;
to[cnt] = a;
cost[cnt] = c;
cnt++;
}
}
for (int i = 1; i <= n; i++) dis[i] = inf, tmp[i] = 0;
dis[1] = 0;
tmp[1] = 1;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= cnt; j++)
{
if (dis[to[j]] > cost[j] + dis[from[j]])
{
dis[to[j]] = cost[j] + dis[from[j]];
}
if (tmp[from[j]] == 1)
tmp[to[j]] = 1;
}
}
for (int i = 1; i <= cnt; i++)
{
if (dis[to[i]] > cost[i] + dis[from[i]]&&(tmp[from[i]] == 1 || tmp[to[i]] == 1))
{
cout << "YE5" << endl;
return;
}
}
cout << "N0" << endl;
return;
}
int main()
{
int t;
cin >> t;
while (t--)
{
solve();
}
return 0;
}