POJ2449 Remmarguts' Date A*算法

题意是让求从st的ed第k短路。。。

考虑A*算法:先把终点到每个点最短路跑出来(注意要建反图),当做估价函数h(u),然后跑A*

每次取出总代价最小的,即g(u)+h(u)最小的进行扩展,注意如果u被取出的次数c[u]>k,就不再进行扩展了。

当ed被取出且c[ed]==k,那么答案就是此时的g(ed)

#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
#define R register int
#define mp make_pair
const int Inf=0x3f3f3f3f,M=100010,N=1010;
using namespace std;
inline int g() {
    R ret=0; register char ch; while(!isdigit(ch=getchar())) ;
    do ret=ret*10+(ch^48); while(isdigit(ch=getchar())); return ret;
}
int n,m,cnt,ccnt,st,ed,k;
int vr[M],w[M],nxt[M],fir[N];
int vv[M],ww[M],nn[M],ff[N],d[N],c[N];
bool vis[N];
inline void add(int u,int v,int ww) {vr[++cnt]=v,w[cnt]=ww,nxt[cnt]=fir[u],fir[u]=cnt;}
inline void add1(int u,int v,int w) {vv[++ccnt]=v,ww[ccnt]=w,nn[ccnt]=ff[u],ff[u]=ccnt;}
inline void dijk() { memset(d,0x3f,sizeof(d));
    priority_queue<pair<int,int> > q; q.push(mp(0,ed)); d[ed]=0;
    while(q.size()) {
        R u=q.top().second; q.pop(); if(vis[u]) continue;
        for(R i=ff[u];i;i=nn[i]) { R v=vv[i];
            if(d[v]>d[u]+ww[i]) d[v]=d[u]+ww[i],q.push(mp(-d[v],v));
        }
    }
}
struct node{ int u,g,h; node() {}
    node(int uu,int gg,int hh) {u=uu,g=gg,h=hh;}
    bool operator <(const node& y) const {return g+h>y.g+y.h;}
};
inline int Astar() { if(d[st]==Inf) return -1;
    priority_queue<node> q; q.push(node(st,0,d[st]));
    while(q.size()) {
        register node crt=q.top(); q.pop(); R u=crt.u; ++c[u]; 
        if(c[u]>k) continue; if(u==ed&&c[u]==k) return crt.g;
        for(R i=fir[u];i;i=nxt[i]) q.push(node(vr[i],crt.g+w[i],d[vr[i]]));
    } return -1;
}
signed main() {
    n=g(),m=g();
    for(R i=1,u,v,w;i<=m;++i) u=g(),v=g(),w=g(),add(u,v,w),add1(v,u,w);
    st=g(),ed=g(),k=g(); st==ed?++k:k; dijk(); printf("%d\n",Astar());
}

2019.04.27

上一篇:E-免费的飞机


下一篇:登录