[AcWing面向模型编程]第k短路

题目:178. 第K短路

分析:模板

代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;//三年竞赛一场空,不开long long见祖宗 
//typedef __int128 lll;
#define print(i) cout << "debug: " << i << endsl
#define close() ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define mem(a, b) memset(a, b, sizeof(a))
#define pb(a) push_back(a)
#define x first
#define y second
typedef pair<int, int> pii;
const ll mod = 1e9 + 7;
const int maxn = 1e5 + 10;
const int inf = 0x3f3f3f3f;
struct edge
{
    int v, val, nex;
}e[maxn << 1];
struct node
{
    int dis, nowdis, u;
    bool operator< (const node b) const{
        return b.dis < dis;
    }
};
int head1[maxn], head2[maxn], tot;

int s, t, k;
int n, m;

int dis[maxn], vis[maxn];
int cnt[maxn];

void init()
{
    mem(head1, -1), mem(head2, -1), tot = 0;
}

void addedge(int head[], int x, int y, int val)
{
    e[tot] = {y, val, head[x]};
    head[x] = tot++;
}

void dj()
{
    mem(dis, inf), dis[t] = 0;
    priority_queue<pii, vector<pii>, greater<pii> > q; q.push({0, t});
    while(!q.empty())
    {
        pii now = q.top(); q.pop();
        int u = now.y;
        if(vis[u]) continue;
        vis[u] = 1;
        for(int i = head2[u]; ~i; i = e[i].nex)
        {
            int v = e[i].v;
            if(dis[v] > dis[u] + e[i].val)
                dis[v] = dis[u] + e[i].val, q.push({dis[v], v});
        }
    }
}

int a_star()
{
    priority_queue<node> q; q.push({dis[s], 0, s});
    while(!q.empty())
    {
        node now = q.top(); q.pop();
        int distance = now.dis, nowdis = now.nowdis, u = now.u;
        cnt[u]++;
        if(cnt[t] == k) return nowdis;
        for(int i = head1[u]; ~i; i = e[i].nex)
        {
            int v = e[i].v;
            if(cnt[v] < k)
                q.push({nowdis + e[i].val + dis[v], nowdis + e[i].val, v});
        }
    }
    return -1;
}

int main()
{
    cin >> n >> m;
    init();
    for(int i = 1; i <= m; i++)
    {
        int a, b, c; cin >> a >> b >> c;
        addedge(head1, a, b, c);
        addedge(head2, b, a, c);
    }
    cin >> s >> t >> k;
    if(t == s) k++;
    dj();
    cout << a_star() << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值