#include <cstdio>
#include <iostream>
#include<vector>
#include<queue>
#include<string.h>
using namespace std;
const int maxn = 1e5 + 10;struct edge {//领链表
int to;//表示到哪个点
int wei;//表示边的权重
edge(int a, int b) {
to = a;
wei = b;
}
};vector<edge>adj[2005];
//adj[u][i].to,u表示起点,to表示第i条边指向的终点
int dis[maxn];//表示单个源点到达u的距离,开始时除源点全部初始化为inf
int vis[maxn];//注意不是如dijkstra算法一样判断是否松弛过,因为spfa算法有负数也就是可以重复松弛一条边,spfa要将所有松弛的终点入队用它来松弛其他连接的点,
//所以vis判断该点是否在队列中
int inque[maxn];//记录某点的入队次数,如果大于n则表示有负环.
int n, m, t, s;
queue<int>q;
bool Spfa() {dis[1] = 0;//将源点距离初始化为1
q.push(1);//将源点入队while (!q.empty()) {//循环
int u = q.front();//队首出队
q.pop();//弹出
vis[u] = 0;//表示u不在队列里了
if (inque[u] > n) {//判断负环
printf("YES\n");
return false;
}
for (int i = 0; i < adj[u].size(); i++) {//把点u连接的所有边都遍历
int tt = adj[u][i].to;//该边指向的点
if (dis[u] + adj[u][i].wei < dis[tt]) {//如果可以松弛
dis[tt] = dis[u] + adj[u][i].wei;//松弛
inque[tt]++;//松弛次数增加
if (!vis[tt]) {//如果v没有入队vis[tt] = 1;//入队
q.push(tt);
}
}
}
}
printf("NO\n");
return true;
}
int main()
{
int u, v, w;
scanf("%d", &t);
while (t--) {
scanf("%d%d", &n, &m);
memset(inque, 0, sizeof(inque));
memset(dis, 0x7f, sizeof(dis));
for (int i = 1; i <= m; i++) {
scanf("%d%d%d", &u, &v, &w);
adj[u].push_back(edge(v, w));
if (w >= 0) adj[v].push_back(edge(u, w));//大于等于0时双向边
}
Spfa();
for (int j = 1; j <= n; j++) {
adj[j].clear();//清空
}
}
}
[图论]负环,SPFA
最新推荐文章于 2024-04-03 23:41:46 发布