POJ2449 Remmarguts' Date 非严格K短路模板题

MLE点:用指针写邻接表MLE了...

WA点:注意s,t相同时,题目的要求,若必须移动,则应求k+1短路

注意spfa求h函数值时,应该是把原图的边都反向后再求到达t的最短距离

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
using namespace std;
#define INF 0x7ffffff
struct edge
{
    int from,to,w,next1,next2;
}ee[100010];
int ecnt,e1[1005],e2[1005],h[1005],cnt[1005],n,m,s,t,k; //cnt应记录出队次数,否则会由于两点间有多条边而出错
bool inq[1005];
struct data
{
    int id,g,h;
    bool operator > (const data &a) const      //注意加const
    {
        return g+h>a.g+a.h;
    }
};
void addedge(int u,int v,int cost)
{
    ee[ecnt].from=u;ee[ecnt].to=v;ee[ecnt].w=cost;ee[ecnt].next1=e1[u];ee[ecnt].next2=e2[v];
    e1[u]=ecnt;e2[v]=ecnt;
    ecnt++;
}
int spfa()
{
    int u,v,d,i,pt;
    deque<int> q;
    memset(inq,false,sizeof(inq));
    memset(cnt,0,sizeof(cnt));
    for(i=0;i<=n;++i)
        h[i]=INF;
    h[t]=0;inq[t]=true;
    q.push_back(t);
    while(!q.empty())
    {
        u=q.front();q.pop_front();cnt[u]++;inq[u]=false;
        if(cnt[u]>=n)
            return 0;
        for(pt=e2[u];pt!=-1;pt=ee[pt].next2)
        {
            v=ee[pt].from;d=ee[pt].w;
            if(h[u]+d<h[v])
            {
                h[v]=h[u]+d;
                if(!inq[v])
                {
                    inq[v]=true;
                    if(!q.empty()&&h[v]<=h[q.front()])
                        q.push_front(v);
                    else
                        q.push_back(v);
                }
            }
        }
    }
    if(h[s]==INF)
        return -1;
    return 1;
}
int kth_shortest()
{
    if(spfa()!=1)
        return -1;
    if(s==t)
        k++; //注意这个,当s==t时,不移动也算一条路,如果题目中强调必须移动的话,求k+1路即可
    memset(cnt,0,sizeof(cnt));
    int pt;
    data u,v;
    priority_queue<data,vector<data>,greater<data> > q;
    u.id=s;u.g=0;u.h=h[s];
    q.push(u);
    while(!q.empty())
    {
        u=q.top();q.pop();cnt[u.id]++;
        if(cnt[u.id]>k)               //出队次数大于k已经对k短路不会产生影响
            continue;
        if(u.id==t&&cnt[u.id]==k)
            return u.g;
        for(pt=e1[u.id];pt!=-1;pt=ee[pt].next1)
        {
            v.id=ee[pt].to;v.g=u.g+ee[pt].w;v.h=h[v.id];
            if(cnt[v.id]>=k)        //同上
                continue;
            q.push(v);
        }
    }
    return -1;
}
int main()
{
    scanf("%d %d",&n,&m);
    ecnt=0;
    memset(e1,-1,sizeof(e1));
    memset(e2,-1,sizeof(e2));
    int u,v,cost;
    for(int i=1;i<=m;++i)
    {
        scanf("%d %d %d",&u,&v,&cost);
        addedge(u,v,cost);
    }
    scanf("%d %d %d",&s,&t,&k);
    printf("%d\n",kth_shortest());
    return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值