[BZOJ1598][Usaco2008 Mar]牛跑步(k短路)

题目描述

传送门

题解

k短路A*算法模板题

代码

#include
#include
#include
#include
#include
#include
using namespace std;
#define N 10005
#define LL long long

int n,m,k,s,t;
int tot,point[N],nxt[N],v[N],_tot,_point[N],_nxt[N],_v[N];LL c[N],_c[N];
LL dis[N],ans[N];bool vis[N];int cnt[N];
struct data
{
    int x;LL g,h;
    bool operator < (const data &a) const
    {
        return g+h>a.g+a.h;
    }
};

void add(int x,int y,LL z)
{
    ++tot; nxt[tot]=point[x]; point[x]=tot; v[tot]=y; c[tot]=z;
    ++_tot; _nxt[_tot]=_point[y]; _point[y]=_tot; _v[_tot]=x; _c[_tot]=z;
}
void spfa()
{
    queue <int> q;
    memset(dis,127,sizeof(dis));
    dis[t]=0;vis[t]=1;q.push(t);
    while (!q.empty())
    {
        int now=q.front();q.pop();
        vis[now]=0;
        for (int i=_point[now];i;i=_nxt[i])
            if (dis[_v[i]]>dis[now]+_c[i])
            {
                dis[_v[i]]=dis[now]+_c[i];
                if (!vis[_v[i]]) vis[_v[i]]=1,q.push(_v[i]);
            }
    }
}
void Astar()
{
    priority_queue  q;
    q.push((data){s,0,dis[s]});
    int size=0;
    while (!q.empty())
    {
        data now=q.top();q.pop();
        ++cnt[now.x];
        if (cnt[now.x]>k) continue;
        if (now.x==t) ans[++size]=now.g;
        if (cnt[t]==k) return;
        for (int i=point[now.x];i;i=nxt[i])
            q.push((data){v[i],now.g+c[i],dis[v[i]]});
    }
}
int main()
{
    scanf("%d%d%d",&n,&m,&k);
    for (int i=1;i<=m;++i)
    {
        int x,y;LL z;
        scanf("%d%d%lld",&x,&y,&z);
        if (x1;
    spfa();
    memset(ans,-1,sizeof(ans));
    Astar();
    for (int i=1;i<=k;++i) printf("%lld\n",ans[i]);
}

你可能感兴趣的:(题解,图论算法)