跳到正文

个人记录

图论-spfa判负环

_Gakki_约 2 分钟
原文
文章信息与版本

文章信息

发布
2021年3月13日
收录
2025年12月12日
更新
2026年11月7日
篇幅
约 2 分钟

版本

  1. v2当前
  2. v1

方法1:spfa时记录每个点的入队次数 >=n 就说明有负环 2:spfa记录到达每个点最短路的边数 边数 >= n 说明有负环 (到一个点的边大于等于n说明经过了重复的点即有环 因为更新的是最短路说明是负环) 通常2比较快

一张图上是否有负环

C++
bool spfa(){
	memset(dis,0,sizeof(dis));//注意距离初始化成0(其实其他数也可以)
	memset(cnt,0,sizeof(cnt));
	memset(vis,0,sizeof(vis));
	queue<int> q;
	for(int i = 1;i <= n;i++){
		q.push(i);//(所有点都入队)可以考虑成为一个超级原点到其他点的距离都为0这并不会影响负环
		vis[i] = 1;
	}
	while(!q.empty()){
		int now = q.front();q.pop();
		vis[now] = 0;
		for(int i = head[now];i != -1;i = e[i].next){
			int to = e[i].to;
			if(dis[to] > dis[now] + e[i].w){
				dis[to] = dis[now]+e[i].w;
				cnt[to] = cnt[now]+1;
				if(cnt[to] >= n) return true;
				if(!vis[to]) q.push(to);
				vis[to] = 1;
			}
		}
	}
	return false;
}

判断从一个点出发是否有负环

C++
bool spfa(){
	memset(dis,0x3f,sizeof(dis));
	memset(cnt,0,sizeof(cnt));
	memset(vis,0,sizeof(vis));
	dis[1] = 0;
	queue<int> q;
	q.push(1);
	vis[1] = 1;
	while(!q.empty()){
		int now = q.front();q.pop();
		vis[now] = 0;
		for(int i = head[now];i != -1;i = e[i].next){
			int to = e[i].to;
			if(dis[to] > dis[now] + e[i].w){
				dis[to] = dis[now]+e[i].w;
				cnt[to] = cnt[now]+1;
				if(cnt[to] >= n) return true;
				if(!vis[to]) q.push(to);
				vis[to] = 1;
			}
		}
	}
	return false;
}
原文