Bellman_Ford算法(求一个点到任意一点的最短距离)

单源最短路问题是固定一个起点,求它到任意一点最短路的问题。

记从起点出发到顶点 i 的最短距离为d[i],则有以下等式成立

d[i]=min{d[j]+(从j到 i 的边的权值)

看代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<stdio.h>
#include<string.h>
#include<cmath>
#include<math.h>
#include<algorithm>
#include<set>
#include<queue>
#include<map>
typedef long long ll;
using namespace std;
const ll mod=1e9+7;
const int maxn=1e3+10;
const int maxk=100+10;
const int maxx=1e4+10;
const ll maxe=1000+10;
#define INF 0x3f3f3f3f3f3f
struct edge
{
    int from,to,cost;
};
edge es[maxe];//
ll d[maxn];//最短距离
int v,e,ans;
void solve(int s)
{
    for(int i=0;i<v;i++)
        d[i]=INF;
    d[s]=0;
    while(true)
    {
        bool updata=false;
        for(int i=0;i<e;i++)
        {
            edge p=es[i];
            if(d[p.from]!=INF&&d[p.to]>d[p.from]+p.cost)//找与其相邻的边,并且更新
            {
                d[p.to]=d[p.from]+p.cost;
               // ans=d[p.to];
                updata=true;
            }
        }
        if(!updata)//当不再有更新时代表所有点的最短距离已经求出来了
            break;
    }
    for(int i=0;i<v;i++)
        cout<<d[i]<<" ";//每个点的d[i]值就是从起点到该点的最短距离
    cout<<endl;
}
int main()
{
    ios::sync_with_stdio(false);
    cin>>v>>e;
    for(int i=0;i<e;i++)
    {
        cin>>es[i].from>>es[i].to>>es[i].cost;//把每条边的起点终点和权值用结构体存起来
    }
    solve(0);//代表从0开始
    return 0;
}
当初的梦想实现了吗,事到如今只好放弃吗~
原文地址:https://www.cnblogs.com/caijiaming/p/9381169.html