POJ2449 Remmarguts' Date A*算法

时间:2021-11-12 13:40:08

题意是让求从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=,N=;
using namespace std;
inline int g() {
R ret=; register char ch; while(!isdigit(ch=getchar())) ;
do ret=ret*+(ch^); 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(,ed)); d[ed]=;
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 -;
priority_queue<node> q; q.push(node(st,,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 -;
}
signed main() {
n=g(),m=g();
for(R i=,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