看别人博客手敲的Bellman Ford模板

#include<cstdio>
#include<string.h>
//数组dis[maxn]记录从源点source到顶点v的路径长度,初始化数组dis[n]为maxint, dis[s]为0;
//以下操作循环执行至多n-1次,n为顶点数:
//	(1)对于每一条边e(u, v),如果dis[u] + w(u, v) < dis[v],则另dis[v] = dis[u]+w(u, v)。w(u, v)为边e(u,v)的权值;
//	(2)若上述操作没有对dis进行更新,说明最短路径已经查找完毕,或者部分点不可达,跳出循环。否则执行下次循环;
//	(3)为了检测图中是否存在负环路,即权值之和小于0的环路。对于每一条边e(u, v),如果存在dis[u] + w(u, v) < dis[v]的边,则图中存在负环路,即是说改图无法求出单源最短路径。否则数组dis[n]中记录的就是源点s到各顶点的最短路径长度。
const int maxn = 100;
const int maxint = 99999;

typedef struct Edge{
	int u,v; //起点,终点
	int weight;  //权重
}Edge;

Edge edge[maxn];	//保存边的值
int dis[maxn];	//源点到结点距离

int nodeNum,edgeNum,source;  //结点数,边数,源点

void Init(){
	scanf("%d %d %d",&nodeNum,&edgeNum,&source);
	for(int i = 1;i<= nodeNum;i++)
		dis[i] = maxint;
	dis[source] = 0;
	for(int i = 1;i<=edgeNum;i++){
		scanf("%d %d %d",&edge[i].u,&edge[i].v,&edge[i].weight);
		if(edge[i].u == source){
			dis[edge[i].v] = edge[i].weight;
		}
	}
}

void relax(int u,int v,int weight){
	if(dis[v] > dis[u] + weight)
		dis[v] = dis[u] + weight;
}

bool Bellman_Ford(){
	for(int i = 1;i<=nodeNum-1;i++)
		for(int j = 1;j<=edgeNum;j++)
			relax(edge[j].u,edge[j].v,edge[j].weight);
	bool flag = 1;
	for(int j = 1;j<=edgeNum;j++){
		if(dis[edge[j].v] > dis[edge[j].u] + edge[j].weight){
			flag = 0;
			break;
		}

	}
	return flag;
}

    原文作者:Bellman - ford算法
    原文地址: https://blog.csdn.net/zzc_doggie/article/details/52988012
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞