Answer POJ 2449 Remmarguts‘ Date 第K短路_题解

Remmarguts’ Date

我来水个题解
结果
使用astar算法,先算出dist[ n ] (直接宽搜每个点到终点的距离)
astar: 估值为(x + dist[x]) x为当前值
代码(main里有防抄_已取消_):




代码:

#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
typedef pair<int, PII> PIII;
const int N = 1010, M = 200010;

//information
int n, m, S, T, K;
int h[N], rh[N], e[M], w[M], ne[M], idx;
int dist[N];
int st[N];

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

//a*
void dijkstra()
{
    priority_queue<PII, vector<PII>, greater<PII> > heap;
    heap.push({ 0, T });
    memset(dist, 0x3f, sizeof dist);
    dist[T] = 0;
    while (heap.size())
    {
        PII t = heap.top();
        heap.pop();
        int ver = t.y;
        if (st[ver]) continue;
        st[ver] = true;
        for (int i = rh[ver]; ~i; i = ne[i])
        {
            int j = e[i];
            if (dist[j] > dist[ver] + w[i])
            {
                dist[j] = dist[ver] + w[i];
                heap.push({ dist[j], j });
            }
        }
    }
}
int astar()
{
    priority_queue<PIII, vector<PIII>, greater<PIII> > heap;
    heap.push({ dist[S], {0, S} });
    memset(st, 0, sizeof st);
    while (heap.size())
    {
        PIII t = heap.top();
        heap.pop();
        int ver = t.y.y, distance = t.y.x;
        st[ver] ++;
        if (ver == T && st[ver] == K) return distance;
        for (int i = h[ver]; ~i; i = ne[i])
        {
            int j = e[i];
            heap.push({ distance + w[i] + dist[j], {distance + w[i], j} });
        }
    }
    return -1;
}

//main
int main()
{
    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;

    //I don't understand it I just follow others...
    if (S == T) ++K;

    dijkstra();

    //Don't just copy!
    cout << astar();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值