#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int N = 1e5 + 10;
int h[N], e[N], w[N], ne[N], idx; // 邻接表存储图的信息,h为头结点数组,e为尾节点数组,w为边的权值数组,ne为下一个节点的索引数组,idx为当前边的索引
int n, m; // n为节点数,m为边数
queue<int> q; // 用于存储待处理的节点
int st[N], dist[N], cnt[N]; // st为标记节点是否在队列中的数组,dist为节点到起点的距离数组,cnt为节点入队的次数数组
void add(int a, int b, int c) { // 添加一条从a到b的权值为c的有向边
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
int spfa() { // spfa算法判断是否存在负环
memset(dist, 0x3f, sizeof dist); // 初始化距离数组为无穷大
for (int i = 1; i <= n; i++) { // 将所有节点加入队列
q.push(i);
st[i] = true;
}
st[1] = true; // 标记起点已入队
while (q.size()) { // 当队列不为空时
int t = q.front(); // 取出队首节点
q.pop(); // 将队首节点出队
st[t] = false; // 标记队首节点已出队
for (int i = h[t]; i != -1; i = ne[i]) { // 遍历队首节点的所有邻接节点
int j = e[i]; // 获取邻接节点
if (dist[j] > dist[t] + w[i]) { // 如果通过当前边可以更新到达邻接节点的距离
dist[j] = dist[t] + w[i]; // 更新距离
cnt[j] = cnt[t] + 1; // 更新入队次数
// 如果超过了n-1
// 根据抽屉原理,说明经过某个节点两次,则说明有环
if (cnt[j] >= n) return true; // 如果入队次数超过n-1,说明存在负环
if (!st[j]) { // 如果邻接节点未入队
st[j] = true; // 标记邻接节点已入队
q.push(j); // 将邻接节点加入队列
}
}
}
}
return false; // 如果队列为空,说明不存在负环
}
int main() {
memset(h, -1, sizeof h); // 初始化邻接表
cin >> n >> m; // 输入节点数和边数
for (int i = 0; i < m; i++) { // 输入每条边的信息
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a, b, c); // 添加边
}
if (spfa()) puts("Yes"); // 如果存在负环,输出Yes
else puts("No"); // 如果不存在负环,输出No
}
852. spfa判断负环
最新推荐文章于 2024-06-25 21:10:30 发布