\[ {\forall}path{\in}S,f[x]{\leq}lenth[path] \]
\[ f[x]{\leq}ShortestPath \]
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#define maxn 1001
#define maxm 100001
using namespace std;
struct graph{
struct edge{
int to,dis,next;
edge(){}
edge(const int &_to,const int &_dis,const int &_next){ to=_to,dis=_dis,next=_next; }
}e[maxm];
int head[maxn],k;
inline void init(){ memset(head,-1,sizeof head); }
inline void add(const int &u,const int &v,const int &w){ e[k]=edge(v,w,head[u]); head[u]=k++; }
}a,b;//a为正图,b为反图
int f[maxn];
bool vis[maxn];
int n,m,s,t;
struct set_elmt{
int id,dis;
set_elmt(){}
set_elmt(const int &_dis,const int &_id){ id=_id,dis=_dis; }
bool operator<(const set_elmt &x)const{ return dis>x.dis; }
};//Dijkstra的优先级
struct node{
int id,dis;
node(){}
node(const int &_dis,const int &_id){ id=_id,dis=_dis; }
bool operator<(const node &x)const{ return dis+f[id]>x.dis+f[x.id]; }
};//A*的优先级
inline int read(){
register int x(0),f(1); register char c(getchar());
while(c<'0'||'9'<c){ if(c=='-') f=-1; c=getchar(); }
while('0'<=c&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar();
return x*f;
}
inline void dijkstra(){
memset(f,0x3f,sizeof f);
priority_queue<set_elmt> q;
q.push(set_elmt(0,t)),f[t]=0;
while(q.size()){
int u=q.top().id; q.pop();
if(vis[u]) continue; vis[u]=true;
for(register int i=b.head[u];~i;i=b.e[i].next){
int v=b.e[i].to;
if(f[v]>f[u]+b.e[i].dis) f[v]=f[u]+b.e[i].dis,q.push(set_elmt(f[v],v));
}
}
}
inline int astar(){
int K=read()+(s==t);//特判(起点=终点)的情况
priority_queue<node> q;
q.push(node(0,s));
while(q.size()){
int u=q.top().id,w=q.top().dis; q.pop();
if(u==t&&--K==0) return w;
for(register int i=a.head[u];~i;i=a.e[i].next){
int v=a.e[i].to;
q.push(node(w+a.e[i].dis,v));
}
}
return -1;
}
int main(){
a.init(),b.init();
n=read(),m=read();
for(register int i=1;i<=m;i++){
int u=read(),v=read(),w=read();
a.add(u,v,w),b.add(v,u,w);
}
s=read(),t=read();
dijkstra();
printf("%d\n",astar());
return 0;
}
原文:https://www.cnblogs.com/akura/p/10871309.html