K短路

#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 2e5 + 5, M = 10000 + 5;
const int INF = 0x3f3f3f3f;
int n, m, k;
struct edge {
    int to, w;
};
vector <edge> G[M];
struct node {
    int id, dis;
    bool operator <(const node &u) const {
        return dis > u.dis;
    }
};
int dis[N];
bool vis[N];
priority_queue<node> q;
void dijkstra(int s) {
    memset(dis, 0x3f, sizeof dis);
    dis[s] = 0;
    q.push({s, dis[s]});
    while (!q.empty()) {
        node u = q.top();
        q.pop();
        if (vis[u.id]) continue;
        vis[u.id] = 1;
        for (auto e : G[u.id]) {
            if (vis[e.to]) continue;
            if (dis[e.to] > u.dis + e.w) {
                dis[e.to] = u.dis + e.w;
                q.push({e.to, dis[e.to]});
            }
        }
    }
}
struct Node {
    int v, g, h;
    bool operator <(const Node &a) const {
        return g + h > a.g + a.h;
    }
};
int cnt[N];
int astar(int s, int t, int k) {
    priority_queue<Node> q;
    q.push({s, 0, 0});
    while (!q.empty()) {
        Node u = q.top();
        q.pop();
        cnt[u.v] ++;
        if (cnt[u.v] == k && u.v == t) return u.g + u.h;
        for (auto e : G[u.v]) {
            q.push({e.to, u.g + e.w, dis[e.to]});
        }
    }
    return -1;
}
signed main() {
    ios::sync_with_stdio(0);
    cin >> n >> m >> k;
    for (int i = 1; i <= m; i ++) {
        int u, v, w;
        cin >> u >> v >> w;
        G[u].push_back({v, w});
        G[v].push_back({u, w});
    }
    dijkstra(n);
    cout << astar(1, n, k);
    return 0;
}
posted @ 2023-05-25 11:09  固态H2O  阅读(4)  评论(0编辑  收藏  举报  来源