Poj2449 第k短路

 模板题

#include<iostream>
#include<queue>
#include<string.h>
#include<stdio.h>
using namespace std;
#define inf 0x3f3f3f3f
struct node
{
    int id,f,g;
};
struct edge
{
    int u,v,val,next;
}e[100005],eopp[100005];
struct cmp
{
    bool operator()(const struct node &a,const struct node &b)
    {

        return a.f>b.f;    //表示按结构体变量里的x成员为比较要素,升序排列
    }
};
int head[1005],headopp[1005],disopp[1005],visopp[1005],cnt[1005]={0};
int n,m,s,t,k;
priority_queue<struct node,vector<struct node>,cmp>mq;
void spfa(int v0)
{
    disopp[v0]=0;
    queue<int>q;
    while(!q.empty()) q.pop();
    q.push(v0);
    visopp[v0]=1;
    while(!q.empty())
    {
        int u=q.front();
        q.pop();
        visopp[u]=0;
        for(int i=headopp[u];i!=-1;i=eopp[i].next)
        {
            int v=eopp[i].v;
            int w=eopp[i].val;
            if(disopp[v]>disopp[u]+w)
            {
                disopp[v]=disopp[u]+w;
                if(!visopp[v])
                {
                    q.push(v);
                    visopp[v]=1;
                }
            }

        }
    }
}
int astar()
{
    struct node tmp;
    tmp.id=s;
    tmp.g=0;
    tmp.f=disopp[s];
    mq.push(tmp);
    while(!mq.empty())
    {
        node now=mq.top();
        mq.pop();
        cnt[now.id]++;
        if(cnt[now.id]>k) continue;
        if(cnt[t]==k) return now.g;
        for(int i=head[now.id];i!=-1;i=e[i].next)
        {
            node next;
            next.id=e[i].v;
            next.g=now.g+e[i].val;
            next.f=next.g+disopp[next.id];;
            mq.push(next);
        }
    }
    return -1;

}
int main()
{
    int b=0;
    cin>>n>>m;
    memset(head,-1,sizeof(head));
    memset(headopp,-1,sizeof(headopp));
    memset(disopp,0x3f,sizeof(disopp));
    memset(visopp,0,sizeof(visopp));
    for(int i=1;i<=m;i++)
    {
        int u,v,w;
        scanf("%d%d%d",&u,&v,&w);
        e[b].u=u;
        e[b].v=v;
        e[b].val=w;
        e[b].next=head[u];
        head[u]=b;
        eopp[b].u=v;
        eopp[b].v=u;
        eopp[b].val=w;
        eopp[b].next=headopp[v];
        headopp[v]=b;
        b++;
    }
    scanf("%d%d%d",&s,&t,&k);
    //cout<<"****"<<endl;
    //cout<<"正边"<<endl;
     //for(int i=1;i<=n;i++)
    //{
        //for(int j=head[i];j!=-1;j=e[j].next)
            //cout<<e[j].u<<" "<<e[j].v<<" "<<e[j].val<<endl;
    //}
    //cout<<"反边"<<endl;
    //for(int i=1;i<=n;i++)
    //{
        //for(int j=headopp[i];j!=-1;j=eopp[j].next)
            //cout<<eopp[j].u<<" "<<eopp[j].v<<" "<<eopp[j].val<<endl;
    //}

    if(s==t) k++;
    spfa(t);
    printf("%d\n",astar());
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40642465/article/details/81256408