Bellman-Ford

#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

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值