1. 程式人生 > >看別人部落格手敲的Bellman Ford模板

看別人部落格手敲的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;
}