启发式搜索

本文介绍了一种算法,用于解决给定图中任意两点间第K条最短路径的问题,允许路径中包含重复边。通过使用优先队列和广度优先搜索等技术,该算法能够有效地找到目标路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目大意:就是给出一个图,然后给出一个起点个一个终点,求这两点间的第K短路。本题中是可以走重复的路的,所以如果一张图中有一个环的话,无论求第几短路都是存在的。

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
const int MAXN = 1000;
const int MAXM = 100000;
struct node
{
    int v, w;
    node *next;
} Edges[MAXM*2+10], *ecnt = Edges, *adj[MAXN+10], *adj1[MAXN+10];
struct State
{
    int f, id;
    bool operator<(const State& s) const
    {
        return f>s.f;
    }
};
priority_queue<State> que;
void addedge(int u, int v, int w)
{
    ++ecnt;
    ecnt->v = v;
    ecnt->w = w;
    ecnt->next = adj[u];
    adj[u] = ecnt;
}
void _addedge(int u, int v, int w)
{
    ++ecnt;
    ecnt->v = v;
    ecnt->w = w;
    ecnt->next = adj1[u];
    adj1[u] = ecnt;
}
int dis[MAXN+10];
bool inque[MAXN+10];
void SPFA(int res)
{
    queue<int> que;
    que.push(res);
    inque[res] = true;
    memset(dis, 0x3f, sizeof dis);
    dis[res] = 0;
    while(!que.empty())
    {
        res = que.front();
        que.pop();
        inque[res] = false;
        for(node *p=adj1[res]; p; p=p->next)
        {
            int v=p->v;
            if(dis[v] > dis[res] + p->w)
            {
                dis[v] = dis[res] + p->w;
                if(!inque[v])
                {
                    inque[v] = true;
                    que.push(v);
                }
            }
        }
    }
}
int main()
{
    int n, m;
    int S, T, K, u, v, w;
    scanf("%d%d", &n, &m);
    for(int i=1; i<=m; i++)
    {
        scanf("%d%d%d", &u, &v, &w);
        addedge(u, v, w);
        _addedge(v, u, w);
    }
    scanf("%d%d%d", &S, &T, &K);
    if(S == T) K++;
    SPFA(T);
    State t1, t2;
    t1.f = dis[S];
    t1.id = S;
    que.push(t1);
    int counter = 0;
    while(!que.empty())
    {
        t1 = que.top();
        que.pop();
        if(t1.id == T)
        {
            counter++;
            if(counter == K)
            {
                printf("%d\n" ,t1.f);
                return 0;
            }
        }
        for(node *p=adj[t1.id]; p; p=p->next)
        {
            int v = p->v;
            t2.f = t1.f - dis[t1.id] + p->w + dis[v];
            t2.id = v;
            que.push(t2);
        }
    }
    printf("-1\n");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值