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

来源:互联网 发布:js table 添加tr td 编辑:程序博客网 时间:2024/06/07 06:05

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 0x7ffffffstruct 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;}


 

原创粉丝点击