#include<bits/stdc++.h>
using namespace std;
struct edge{
int from,to,cost;
};
edge es[100]; //结构体存边
int v,e,s; //顶点数、边数、起点编号
int d[100]; //顶点S出发到所有点最短距
bool find_negative_loop(){
memset(d,0,sizeof(d));
for(int i=0;i<v;i++){
for(int j=0;j<e;j++){
edge e=es[j];
if(d[e.to]>d[e.from]+e.cost){
d[e.to]=d[e.from]+e.cost;
if(i==v-1)
return true;
}
}
}
return false;
}
int main(){
cin>>v>>e>>s;
for(int i=0;i<e;i++) cin>>es[i].from>>es[i].to>>es[i].cost;
for(int i=0;i<v;i++) d[i]=10000; //距离数组初始化最大
d[s]=0; //起点距离为0
while(true)
{
bool update=false; //判断是否更新的标志位
for(int i=0;i<e;i++)
{
edge e=es[i]; //读出当前的边并松驰
if(d[e.from]!=10000&&d[e.to]>d[e.from]+e.cost){
d[e.to]=d[e.from]+e.cost;
update=true;
}
}
if(!update)break; //没有更新就退出
}
for(int i=0;i<v;i++)
cout<<d[i]<<endl;
return 0;
}
单源最短路
Bellman-Ford
Input output
5 4 0 0
0 1 1 1
1 2 3 4
3 4 5 8
2 3 4 13