Bellman-ford算法的一个重要应用是判负环。在迭代n-1次后如果还可以进行松弛操作,说明一定存在负环。如果采用队列实现,那么当某个结点入队了n次时可以判断出存在负环,代码如下:
#include<iostream>
#include<vector>
#include<queue>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
const int maxn = 1001;
struct Edge
{
int from;
int to;
int dist;
};
struct BellmanFord
{
int n,m;
vector<Edge> edges;
vector<int> G[maxn];
bool inq[maxn]; //是否在队列中
int d[maxn]; //s到各个点的距离
int p[maxn]; //最短路中的上一条弧
int cnt[maxn]; //进队次数
void init(int n)
{
this->n = n;
for(int i=0;i<n;i++) G[i].clear();
edges.clear();
}
void AddEdge(int from,int to,int dist)
{
edges.push_back((Edge) {from,to,dist}); //输入相连通的两条边
m = edges.size();
G[from].push_back(m-1);
}
bool negetiveCycle()
{
queue<int> Q;
memset(inq,0,sizeof(inq));
memset(cnt,0,sizeof(cnt));
for(int i=0;i<n;i++) {d[i] = 0;inq[0] = true;Q.push(i);}
while(!Q.empty())
{
int u = Q.front();
Q.pop();
inq[u] = false;
for(int i=0;i<G[u].size();i++)
{
Edge& e = edges[G[u][i]];
if(d[e.to] > d[u] + e.dist)
{
d[e.to] = d[u] + e.dist;
p[e.to] = G[u][i];
if(!inq[e.to]) {Q.push(e.to);inq[e.to] = true;if(++cnt[e.to] > n) return true;}
}
}
}
return false;
}
};
int main()
{
BellmanFord bell;
int start,end,dist;
int i,n,m;
cout<<"please enter n vectex:"<<endl;
//freopen("111","r",stdin);
cin>>n;
bell.init(n);
cout<<"please enter m numbers vectex which two connect:"<<endl;
cin>>m;
for(i=0;i<m;i++)
{
cin>>start>>end>>dist;
bell.AddEdge(start,end,dist);
}
if(bell.negetiveCycle())
{
cout<<"exist negative ring."<<endl;
}
else
{
cout<<"don't exist negative ring."<<endl;
}
return 0;
}