基础算法学习--Bellman_ford算法

适用范围

1.有负环存在
2.有边数限制

模板

#include<iostream>
#include<algorithm>
#include<cstring>

using namespace std;

const int N = 510,M = 10010;

int dist[N];        //距离
int backup[N];      //备份
int n,m,k;

//所有的边
struct Ed{
    int a,b,w;
} e[M];

int bellman_ford(){
    memset(dist,0x3f,sizeof dist);
    dist[1] = 0;

//遍历有限最短路
    for(int i = 0;i < k;i ++){
        memcpy(backup,dist,sizeof dist);

//遍历所有边
        for(int j = 0;j < m;j ++){
            //更新最短路
            int a = e[j].a,b = e[j].b,w = e[j].w;
            dist[b] = min(dist[b],backup[a] + w);
        }
    }

    if(dist[n] > 0x3f3f3f3f / 2) return -1;
    return dist[n];
}

int main(){
    cin >> n >> m >> k;

    for(int i = 0 ;i < m;i ++){
        int a,b,c;
        cin >> a >> b >> c;

        e[i] = {a,b,c};
    }

    int t = bellman_ford();
    if(t == -1) cout << "impossible";
    else cout << t;
}
上一篇:最短路bellman-ford与spfa


下一篇:No.6.3 最短路径之Bellman-Ford算法--解决负权边