第K短路-A*算法

视频链接

https://www.bilibili.com/video/BV19k4y1K7gV

题目链接

题目链接

题面

在这里插入图片描述

代码

#include <bits/stdc++.h>
#define pii pair<int, int>
#define all(sbe) sbe.begin(),sbe.end()
// #define int long long
using namespace std;
typedef long long ll;

const int N = 1010, M = 20010;
int h[N], rh[N], e[M], ne[M], w[M], idx;
int dist[N];
void add(int he[], int a, int b, int c) {
    e[idx] = b, w[idx] = c, ne[idx] = he[a], he[a] = idx ++;
}
signed main(){
#ifdef LOCAL
    freopen("in.txt", "r", stdin);
#endif
    
    memset(h, -1, sizeof(h));
    memset(rh, -1, sizeof(rh));

    int n, m, S, T, K; cin >> n >> m;
    for(int i = 1; i <= m; i++) {
        int a, b, c; cin >> a >> b >> c;
        add(h, a, b, c); add(rh, b, a, c); 
        // 第二个add建反向图求估价函数 这里使用dijkstra求出估价函数值等于真实值
    }
    cin >> S >> T >> K;
    if(S == T) K ++; // 起点与终点重合求第K+1短路
    if(m == 0) {
        cout << "-1\n";
        return 0;
    }

    function<void()> dijkstra = [&](){
        memset(dist, 0x3f, sizeof(dist));
        dist[T] = 0;
        vector<bool> vis(N, false);
        priority_queue<pii> pq;
        pq.push({0, T});

        while(pq.size()) {
            auto t = pq.top().second; pq.pop();
            
            if(vis[t]) continue;
            vis[t] = 1;

            for(int i = rh[t]; i != -1; i = ne[i]) {
                int j = e[i];
                if(dist[j] > dist[t] + w[i]) {
                    dist[j] = dist[t] + w[i];
                    pq.push({-dist[j], j});
                }
            }
        }
    };

    function<void()> bfs = [&](){
        vector<int> con(N, 0);
        using tp3 = tuple<int, int, int>;
        priority_queue<tp3, vector<tp3>, greater<tp3>> pq;
        pq.push({dist[S], 0, S});

        while(pq.size()) {
            auto [x, y, z] = pq.top(); pq.pop();

            con[z] ++;
            if(con[T] == K) {
                cout << y << '\n';
                return ;
            }

            for(int i = h[z]; i != -1; i = ne[i]) {
                int j = e[i];
                if(con[j] < K) {
                    pq.push({y + w[i] + dist[j], y + w[i], j});
                }
            }
        }

        cout << "-1\n";
        return ;
    };

    dijkstra();
    bfs();
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值