贝尔曼最短路径算法

时间复杂度为O(n*n) 比Dijkstra算法慢,但是能够检查负圈

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <queue>
#include <cmath>
#include <fstream>
const int MAX = 1e5+10;
const int INF = 1e6;

using namespace std;

struct edge_ {
	int from, to, cost;
};

edge_ es[MAX];
int d[MAX];
int V,E;

void Sp(int s){
	//初始化 
	fill(d, d+V, INF);
	d[s] = 0;
	//循环 
	while(true){
		bool update = false;
		//遍历每条边 
		for(int i=0; i<2*E; i++){
			edge_ e = es[i];
			// d[e.from]已经更新过,d[e.to]没有更新过或者不是最短路径 
			if(d[e.from]!=INF && d[e.to]>d[e.from]+e.cost){
				d[e.to] = d[e.from] + e.cost;
				update = true;
			}
		}//如果本次遍历没有更新  也就是说全部都是最短路径  跳出 
		if(!update) break;
	}
}

//测试函数 
int main(){
	ifstream cin ("D:\\钢铁程序员\\程序数据\\003最短路径.txt");//从文件读取数据流,省去手动输入的麻烦 
	if(!cin){//读取如果失败 
		cout << "ERROR" << endl;
	}
	cin >> V >> E;
	for(int i=0; i<E; i++){
		int a, b, c;
		cin >> a >> b >> c;
		//无向图,双向 
		es[i].to = a;
		es[i].from = b;
		es[i].cost = c;
		es[i+E].to = b;
		es[i+E].from = a;
		es[i+E].cost = c;
	}
	Sp(0);
	cout << d[V-1] << endl;
	cin.close();//打开文件以后要关闭 
	return 0;
} 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值