K短路问题模板(spfa+A*)

k短路问题

给一个图,起点s、终点t、k,求起点到终点的第k短路。
基本思路:
首先spfa求出反向图中求出终点t到其他所有点的距离(预处理)
再从起点开始使用优先队列进行宽搜,用cnt记录到达终点的次数,当cnt==k时的路径长度即为所得。
搜索的方向用一个估价函数f=g+dis来确定,其中g表示起点到当前点的路径长度,dis表示当前点到终点的最短路径(即之前的预处理),每次扩展估价函数值最小的一个。

#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int maxn=100010;
int n,m,dis[maxn];
int tot,head1[maxn],head2[maxn];
bool flag[maxn];
struct edge
{
    int to;
    int w;
    int next;
}e[maxn*2],e2[maxn*2];
struct node
{
    int f;//f=g+dis dis表示当前点到终点的最短路径,即之前的预处理
    int g;//g表示到当前点的路径长度
    int from;
    bool operator < (node a)const
    {
        if(a.f==f)
        return g>a.g;//重载 小的在前面 
        return f>a.f;
    }
};
void add_edge(int u,int v,int w)
{
    tot++;
    e[tot].to=v;
    e[tot].w=w;
    e[tot].next=head1[u];
    head1[u]=tot;
    e2[tot].to=u;//建反图
    e2[tot].w=w;
    e2[tot].next=head2[v];
    head2[v]=tot;
}
void spfa(int t)//反图预处理dis
{
    for(int i=1;i<=n;i++)
    dis[i]=maxn;
    dis[t]=0;
    queue<int> q;
    q.push(t);
    flag[t]=1;
    while(!q.empty())
    {
        int v=q.front();
        q.pop();flag[v]=0;
        for(int i=head2[v];i;i=e2[i].next)
        if(dis[e2[i].to]>dis[v]+e2[i].w)
        {
            dis[e2[i].to]=dis[v]+e2[i].w;
            if(!flag[e2[i].to])
            {
                q.push(e2[i].to);
                flag[e2[i].to]=1;
            }
        }
    }
}
int a_star(int s,int t,int k)
{
    if(s==t) return 0;
    if(dis[s]==maxn) return -1;
    priority_queue<node> q;
    int cnt=0;
    node tmp,to;
    tmp.from=s;
    tmp.g=0;
    tmp.f=tmp.g+dis[tmp.from];
    q.push(tmp);
    while(!q.empty())
    {
        tmp=q.top();
        q.pop();
        if(tmp.from==t) cnt++;
        if(cnt==k) return tmp.g;
        for(int i=head1[tmp.from];i;i=e[i].next)
        {
            to.from=e[i].to;
            to.g=tmp.g+e[i].w;
            to.f=to.g+dis[to.from];
            q.push(to);
        }
    }
    return -1;
}
int main()
{
    int x,y,z,s,t,k;
    cin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        cin>>x>>y>>z;
        add_edge(x,y,z);
    }
    cin>>s>>t>>k;//输入起点,终点,k短路
    spfa(t);
    int ans=a_star(s,t,k);
    cout<<ans;
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值