自学内容网 自学内容网

[C++][算法基础]边数限制最短路径(BellmanFord)

给定一个 n 个点 m 条边的有向图,图中可能存在重边和自环, 边权可能为负数

请你求出从 1 号点到 n 号点的最多经过 k 条边的最短距离,如果无法从 1 号点走到 n 号点,输出 impossible

注意:图中可能 存在负权回路 。

输入格式

第一行包含三个整数 n,m,k。

接下来 m 行,每行包含三个整数 x,y,z,表示存在一条从点 x 到点 y 的有向边,边长为 z。

点的编号为 1∼n。

输出格式

输出一个整数,表示从 1 号点到 n 号点的最多经过 k 条边的最短距离。

如果不存在满足条件的路径,则输出 impossible

数据范围

1≤n,k≤500,
1≤m≤10000,
1≤x,y≤n,
任意边长的绝对值不超过 10000。

输入样例:
3 3 1
1 2 1
2 3 1
1 3 3
输出样例:
3

 代码:

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;

const int M = 510,N = 10010;
int dist[M],standby[M];
int n,m,k,a,b,w;

struct Edge{
    int A;
    int B;
    int W;
}Edge[N];

int bellmanford_Sort(){
    dist[1] = 0;
    for(int i = 0;i < k;i++){
        memcpy(standby,dist,sizeof dist);
        for(int j = 0;j < m;j++){
            int A = Edge[j].A;
            int B = Edge[j].B;
            int W = Edge[j].W;
            dist[B] = min(standby[A] + W, dist[B]);
        }    
    }
    if(dist[n] > 0x3f3f3f3f >> 1){
        return -0x3f3f3f3f;
    }else{
        return dist[n];
    }
}

int main(){
    cin>>n>>m>>k;
    memset(dist,0x3f3f3f3f,sizeof dist);
    for(int i = 0;i < m;i++){
        cin>>a>>b>>w;
        Edge[i] = {a,b,w};
    }
    int now = bellmanford_Sort();
    if(now == -0x3f3f3f3f){
        cout<<"impossible";
    }else{
        cout<<dist[n];
    }
    return 0;
}


原文地址:https://blog.csdn.net/Caveira271_/article/details/137683228

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!