[AcWing 178] 第K短路

image

A* 算法


点击查看代码
#include<bits/stdc++.h>

using namespace std;

typedef long long LL;
typedef pair<int,int> PII;
typedef pair<int,PII> PIPII;

const int N = 1e6 + 10;

int n, m, S, T, K;
int h[N], rh[N], e[N], ne[N], w[N], idx;
int d[N], cnt[N];
bool st[N];

void add(int h[], int a, int b, int c)
{
    e[idx] = b;
    w[idx] = c;
    ne[idx] = h[a];
    h[a] = idx ++;
}

void dijkstra()
{
    priority_queue<PII, vector<PII>, greater<PII>> heap;
    heap.push({0, T});
    memset(d, 0x3f, sizeof d);
    d[T] = 0;
    while (heap.size()) {
        auto t = heap.top();
        heap.pop();
        int v = t.second;
        if (st[v])
            continue;
        st[v] = true;
        for (int i = rh[v]; i != -1; i = ne[i]) {
            int j = e[i];
            if (d[j] > d[v] + w[i]) {
                d[j] = d[v] + w[i];
                heap.push({d[j], j});
            }
        }
    }
}

int astar()
{
    priority_queue<PIPII, vector<PIPII>, greater<PIPII>> heap;
    heap.push({d[S], {0, S}});
    while (heap.size()) {
        auto t = heap.top();
        heap.pop();
        int v = t.second.second, dist = t.second.first;
        cnt[v] ++;
        if (cnt[T] == K)
            return dist;
        for (int i = h[v]; i != -1; i = ne[i]) {
            int j = e[i];
            if (cnt[j] < K)
                heap.push({dist + w[i] + d[j], {dist + w[i], j}});
        }
    }
    return -1;
}

void solve()
{
    cin >> n >> m;
    memset(h, -1, sizeof h);
    memset(rh, -1, sizeof rh);
    for (int i = 0; i < m; i ++) {
        int a, b, c;
        cin >> a >> b >> c;
        add(h, a, b, c);
        add(rh, b, a, c);
    }
    cin >> S >> T >> K;
    if (S == T)
        K ++;
    dijkstra();
    cout << astar() << endl;
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    solve();

    return 0;
}

  1. 估价函数
    每个点到终点的最短距离,A 算法只要保证估价值小于真实值即可
  2. A算法过程
    ① 建立反图,然后在反图上求出从终点到其他所有点的最短距离,作为每个点的估价函数
    ② 从起点开始扩展,每次取出当前的估计值最小的点,将其所有能扩展到的点全部扩展
    =+
    ③ 当第 k 次遇到终点时,就求出了从起点到终点的第 k 短路
posted @   wKingYu  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
欢迎阅读『[AcWing 178] 第K短路』
点击右上角即可分享
微信分享提示