#include <iostream>
#include <queue>
using namespace std;
const int N = 100010;
int n,m;//节点数 边数
int Cnt[N];//记录一个点 由他邻居节点更新最短距离的次数 若>= n则存在负权
bool IsInQueue[N];//判断节点是否在队列中
int Head[N],Value[N],Next[N],Weight[N],Index; //邻接表
int Dis[N];//最短距离的记录
//邻接表的加边
void AddEdge(int nStart, int nEnd, int nWeight)
{
Value[Index] = nEnd;
Weight[Index] = nWeight;
Next[Index] = Head[nStart];
Head[nStart] = Index;
Index++;
}
//以s为起点 到其他点的最短距离 以及判断s到其他节点是否存在负环
int SPFA(int s)
{
//也可以换种写法 不要参数 直接将全部节点入队列
fill(Dis, Dis+N, 0x3f3f3f3f);
Dis[s] = 0;
queue<int>Queue;
Queue.push(s);
IsInQueue[s] = true;
/*
判断图中有没有负环 不是单一的节点
Dis数组也不用初始化 函数参数也不要
Queue<int>Queue
for(int i = 1; i <= n; i++)
{
IsInQueue[i] = true;
Queue.push(i);
}
*/
while(Queue.size())
{
int t = Queue.front();
Queue.pop();
IsInQueue[t] = false;
//遍历节点t的邻居
for(int i = Head[t]; i != -1; i = Next[i])
{
int j = Value[i];
if(Dis[j] > Dis[t] + Weight[i])
{
Dis[j] = Dis[t] + Weight[i];
if(!IsInQueue[j])
{
Queue.push(j);
IsInQueue[j] = true;
//记录由邻居节点更新的次数
Cnt[j]++;
if(Cnt[j] >= n)
{
return 1;
}
}
}
}
}
return 0;
}
int main(int argc, char** argv)
{
scanf("%d%d",&n, &m);
//初始化头结点数组
fill(Head, Head+N, -1);
for(int i = 0; i < m; i++)
{
int nStart,nEnd,nWeight;
scanf("%d%d%d",&nStart, &nEnd, &nWeight);
AddEdge(nStart, nEnd, nWeight);
}
//判断从1出发有没有负环
if(SPFA(1)) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
return 0;
}
SPFA算法判断负环
最新推荐文章于 2022-07-19 11:41:13 发布
这篇博客介绍了如何利用SPFA(Shortest Path Faster Algorithm)算法来检测图中是否存在负权环。通过建立邻接表并进行最短路径更新,当某节点的最短距离更新次数超过节点总数时,可以判断存在负权环。代码示例展示了从节点1出发进行检查的过程。
2081

被折叠的 条评论
为什么被折叠?



