bellman_ford 队列优化模板

#include<cstdio> 
#include<iostream>
#include<vector>
#include<cstring>
#include<queue>
using namespace std;
const int INF=1000000000 +10;
const int N=10000;

int inq[N],cnt[N],dis[N],p[N],n;
struct node{
	int u,d;
	node(int u,int d):u(u),d(d){}
};

vector<node>edge[N];
bool bellman_ford(int s){
	queue<int>Q;
	memset(inq,0,sizeof(inq));
	memset(cnt,0,sizeof(cnt));
	for(int i=0;i<n;i++)dis[i]=INF;
	dis[s]=0;
	inq[s]=true;
	Q.push(s);
	while(!Q.empty()){
		int u=Q.front();Q.pop();
		inq[u]=false;
		for(int i=0;i<edge[u].size();i++){
			node y=edge[u][i];
			if(dis[u]<INF && dis[y.u]> dis[u]+y.d){
				dis[y.u]=dis[u]+y.d;
				p[y.u]=u;
				if(!inq[y.u]){
					Q.push(y.u);inq[y.u]=true;
					if(++cnt[y.u]>n)return false;
				}
			}
		}
	}
}
int main(){
	int a,b,d,m;
	while(scanf("%d%d",&n,&m)==2 &&n){
		for(int i=0;i<n;i++)edge[i].clear();
		while(m--){
			scanf("%d%d%d",&a,&b,&d);
			edge[a].push_back(node(b,d));
			edge[b].push_back(node(a,d));
		}
		if(bellman_ford(0)) {
			for(int i=0;i<n;i++)cout<<i<<" "<<dis[i]<<endl;
		}
		else cout<<"false"<<endl;
	}
}
    原文作者:Bellman - ford算法
    原文地址: https://blog.csdn.net/love_phoebe/article/details/80256575
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞