转载请注明出处:http://blog.csdn.net/a1dark
#include<stdio.h> #include<string.h> #include<queue> #include<algorithm> using namespace std; #define INF 0x7ffffff #define MAXM 100005 #define MAXN 1005 struct node { int to,next,val; }edge[MAXM],edge1[MAXM]; struct node1 { int g,h; int to; bool operator<(node1 a)const { if(a.h==h)return a.g<g; return a.h<h; } }; int head[MAXN],head1[MAXN]; int dist[MAXN]; int vis[MAXN]; int Q[MAXM*5]; int n,m,k,k1; void add(int x,int y,int val) { edge[k].to=y; edge[k].val=val; edge[k].next=head[x]; head[x]=k++; } void add1(int x,int y,int val) { edge1[k1].to=y; edge1[k1].val=val; edge1[k1].next=head1[x]; head1[x]=k1++; } void init() { k=k1=0; memset(head,-1,sizeof(head)); memset(head1,-1,sizeof(head1)); } void spfa(int s) { memset(vis,0,sizeof(vis)); for(int i=1;i<=n;i++) dist[i]=INF; dist[s]=0; int h=0,t=1; Q[0]=s; vis[1]=1; while(h<t) { int now=Q[h++]; vis[now]=0; for(int i=head1[now];i!=-1;i=edge1[i].next) { int w=edge1[i].to; if(dist[w]-dist[now]>edge1[i].val) { dist[w]=dist[now]+edge1[i].val; if(!vis[w]) { Q[t++]=w; vis[w]=1; } } } } } int Astar(int s,int e,int kth) { int cnt=0; priority_queue<node1>q; node1 now,next; now.to=s; now.g=0; now.h=dist[s]; q.push(now); while(!q.empty()) { next=q.top(); q.pop(); if(next.to==e) { cnt++; if(cnt==kth)return next.g; } for(int i=head[next.to];i!=-1;i=edge[i].next) { now.to=edge[i].to; now.g=next.g+edge[i].val; now.h=now.g+dist[now.to]; q.push(now); } } return -1; } int main() { init(); scanf("%d%d",&n,&m); int a,b,v; int s,t,kth; for(int i=0;i<m;i++) { scanf("%d%d%d",&a,&b,&v); add(a,b,v); add1(b,a,v); } scanf("%d%d%d",&s,&t,&kth); if(s==t)kth++; spfa(t); int ans=Astar(s,t,kth); printf("%d\n",ans); return 0; }
POJ 2449 Remmarguts' Date(A*+SPFA)K短路问题,布布扣,bubuko.com
POJ 2449 Remmarguts' Date(A*+SPFA)K短路问题
原文:http://blog.csdn.net/a1dark/article/details/23031719