求第s~t 第k短的路
先求出所有点到t的最短路径,这可以通过保存逆邻接表来求
这是求出h(u)的精确值dist[u],g()就是离s(起点)点经过多少距离
从优先队列里取出f最小的点,该点扩展数加1,扩展他连接的点,放入优先队列
原理类似Dijkstra,扩展到的点就是s出发最短路径,第i次扩展到u点就是到u点的第i短路径
#include<iostream>
#include<cstdio>
#include<vector>
#include<queue>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long LL;
const int maxn=1000+5;
struct Point{
int to,weight;
Point(int t,int w):to(t),weight(w){}
};
vector<vector<Point> > G(maxn),GT(maxn);
int n,m;
int dist[maxn],inq[maxn];
struct Node{
int to;
int f,g,h;
Node(int to,int g):to(to),g(g){h=dist[to];f=g+h;}
bool operator < (const Node& n) const {
if(f==n.f) return g>n.g;
return f>n.f;
}
};
void Spfa(int s)
{
memset(dist,0x6f,sizeof(dist));
queue<int> Q;
dist[s]=0;
inq[s]=true;
Q.push(s);
while(!Q.empty())
{
int u=Q.front(); Q.pop();
inq[u]=false;
for(int i=0;i<GT[u].size();i++)
{
int v=GT[u][i].to, w=GT[u][i].weight;
if(dist[v]>dist[u]+w)
{
dist[v]=dist[u]+w;
if(!inq[v]) Q.push(v),inq[v]=true;
}
}
}
}
int closed[maxn];
int A_Star(int s,int t,int k)
{
if(dist[s]==dist[0]) return -1;
if(s==t) k++;
memset(closed,0,sizeof(closed));
priority_queue<Node> open;
open.push(Node(s,0));
while(!open.empty())
{
int u=open.top().to,g=open.top().g; open.pop();
closed[u]++;
if(closed[t]==k) return g;
for(int i=0;i<G[u].size();i++)
{
int v=G[u][i].to,w=G[u][i].weight;
open.push(Node(v,g+w));
}
}
return -1;
}
int main()
{
int n,m,u,v,w,s,t,k;
cin>>n>>m;
while(m--)
{
cin>>u>>v>>w;
G[u].push_back(Point(v,w));
GT[v].push_back(Point(u,w));
}
cin>>s>>t>>k;
Spfa(t);
cout<<A_Star(s,t,k)<<endl;
return 0;
}