时间复杂度为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;
}