1. 程式人生 > >POJ2449 Remmarguts' Date A*算法

POJ2449 Remmarguts' Date A*算法

amp 題意 getc ++ inline def opera 擴展 函數

題意是讓求從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

POJ2449 Remmarguts' Date A*算法