BZOJ 1598 牛跑步

Posted on 2017-10-07 10:14  ziliuziliu  阅读(120)  评论(0编辑  收藏  举报

K短路,A*

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#define maxv 1050
#define maxe 10050
#define inf 1000000007
using namespace std;
int n,m,k,x,y,z,g1[maxv],g2[maxv],dis[maxv],nume1=0,nume2=0,ans[maxv];
struct pnt
{
    int id,val,val1;
    friend bool operator < (const pnt &x,const pnt &y)
    {
        return x.val>y.val;
    }
    pnt (int id,int val,int val1):id(id),val(val),val1(val1) {}
    pnt () {}
};
struct edge
{
    int v,w,nxt;
}e1[maxe],e2[maxe];
priority_queue <pnt> q;
queue <int> qr;
bool vis[maxv];
void addedge(int u,int v,int w)
{
    e1[++nume1].v=v;e1[nume1].w=w;e1[nume1].nxt=g1[u];g1[u]=nume1;
    e2[++nume2].v=u;e2[nume2].w=w;e2[nume2].nxt=g2[v];g2[v]=nume2;
}
void spfa()
{
    for (int i=2;i<=n;i++) dis[i]=inf;
    qr.push(1);memset(vis,false,sizeof(vis));
    while (!qr.empty())
    {
        int head=qr.front();qr.pop();vis[head]=false;
        for (int i=g2[head];i;i=e2[i].nxt)
        {
            int v=e2[i].v;
            if (dis[v]>dis[head]+e2[i].w)
            {
                dis[v]=dis[head]+e2[i].w;
                if (!vis[v]) {qr.push(v);vis[v]=true;}
            }
        }
    }
}
void A_star()
{
    q.push(pnt(n,0,0));
    while (!q.empty())
    {
        pnt head=q.top();q.pop();
        if (head.id==1)
        {
            ans[++ans[0]]=head.val1;
            if (ans[0]==k) return;
        }
        for (int i=g1[head.id];i;i=e1[i].nxt)
        {
            int v=e1[i].v;
            pnt ret;
            ret.id=v;ret.val1=head.val1+e1[i].w;ret.val=ret.val1+dis[v];
            q.push(ret);
        }
    }
}
int main()
{
    scanf("%d%d%d",&n,&m,&k);
    for (int i=1;i<=m;i++)
    {
        scanf("%d%d%d",&x,&y,&z);    
        addedge(x,y,z);
    }    
    spfa();
    A_star();
    for (int i=1;i<=k;i++)
    {
        if (!ans[i]) printf("-1\n");
        else printf("%d\n",ans[i]); 
    }
    return 0;
}