

思路:
运用 SPFA算法 结合 抽屉原理 判断图中是否存在负环
时间复杂度:
O(nm) n 表示点数,m 表示边数
代码:
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int N = 2000+10;
const int M = 10000+10;
#define inf 0x3f3f3f3f
int h[M],e[M],ne[M],w[M],idx; // 邻接表存储所有边
int dist[N],cnt[N]; // dist[x]存储1号点到x的最短距离,cnt[x]存储1到x的最短路中经过的点数
bool st[N];// 存储每个点是否在队列中
int x,y,z,n,m;
void add(int x,int y,int z)
{
e[idx]=y,ne[idx]=h[x],h[x]=idx,w[idx]=z,idx++;
}
// 如果存在负环,则返回true,否则

本文介绍了一种使用SPFA(最短路径First-Farthest-Search)算法,结合抽屉原理判断无向图中是否存在负环的方法。通过计算两点之间的最短路径,当经过的节点数超过点数减一(除自身外)时,依据抽屉原理推断存在环。该算法的时间复杂度为O(nm),适用于点数n和边数m的图。
最低0.47元/天 解锁文章
452

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



