第K短路模板题。思路具体如下:
首先在我们求s到t的最短路的时候,如果使用bfs求的话,那么第k次到达的路径长度就是我们要求的第k短路,因此用bfs跑k次不同的到达终点的路径即可。
问题是搜索k次的状态数可能会非常大……所以可以用A* 算法弄一个估价函数出来,如果判断出是比第k短路还长的路径就剪掉
估价函数模型为f=x+e,其中x是当前已经走了的路径长度,e是x到终点的最短路径长度。显然存反向边跑一次dijkstra就可以求得e。至于“剪枝”操作,在bfs中使用优先队列,每次弹出股价函数最短的就行了,这样就可以保证所有不可能出现的情况都在队尾
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
#include<cmath>
#include<map>
#define LL long long
using namespace std;
const LL inf=1e15;
const LL maxn=8e4+5;
inline void _read(LL &x){
char t=getchar();bool sign=true;
while(t<'0'||t>'9')
{if(t=='-')sign=false;t=getchar();}
for(x=0;t>='0'&&t<='9';t=getchar())x=x*10+t-'0';
if(!sign)x=-x;
}
LL N,M,k;
struct Edge{
LL from,to,dist;
Edge(LL from,LL to,LL dist):from(from),to(to),dist(dist){}
};
struct HeapNode{
LL d,u;
HeapNode(LL d,LL u):d(d),u(u){}
bool operator <(const HeapNode& h)const{
return d>h.d;
}
};
struct Dijkstra{
LL n,m,dis[1505];
bool vis[1505];
vector<LL>G[1505];
vector<Edge>edges;
void init(LL n){
this->n=n;
for(LL i=1;i<=n;i++)G[i].clear();
edges.clear();
}
void add_edges(LL from,LL to,LL dist){
edges.push_back(Edge(from,to,dist));
G[from].push_back(edges.size()-1);
m=edges.size();
}
void dijkstra(LL s){
priority_queue<HeapNode>q;
for(LL i=1;i<=n;i++)dis[i]=inf;
dis[s]=0;
memset(vis,0,sizeof(vis));
q.push(HeapNode(0,s));
while(q.size()){
HeapNode x=q.top();q.pop();
LL u=x.u;
if(vis[u])continue;
vis[u]=1;
for(LL i=0;i<G[u].size();i++){
Edge& e=edges[G[u][i]];
if(dis[e.to]>dis[u]+e.dist){
dis[e.to]=dis[u]+e.dist;
q.push(HeapNode(dis[e.to],e.to));
}
}
}
}
}Graph_re;
struct Status{
LL to,d;
Status(LL to,LL d):to(to),d(d){}
bool operator <(const Status& h)const{
return d+Graph_re.dis[to]>h.d+Graph_re.dis[h.to];
}
};
vector<LL>G[1505];
vector<Edge>edges;
void add_edges(LL from,LL to,LL dist){
edges.push_back(Edge(from,to,dist));
G[from].push_back(edges.size()-1);
}
LL bfs(LL s,LL t){
priority_queue<Status>q;
q.push(Status(s,0));
while(q.size()){
Status x=q.top();q.pop();
if(x.to==t){
k--;
if(k==0)return x.d;
}
for(LL i=0;i<G[x.to].size();i++){
Edge& e=edges[G[x.to][i]];
q.push(Status(e.to,x.d+e.dist));
}
}
return -1;
}
int main(){
_read(N);_read(M);_read(k);
LL s,t,x,y,z;
_read(s);_read(t);
Graph_re.init(N);
for(LL i=1;i<=M;i++){
_read(x);_read(y);_read(z);
add_edges(x,y,z);
Graph_re.add_edges(y,x,z);
}
Graph_re.dijkstra(t);
if(Graph_re.dis[s]==inf){
puts("-1");
return 0;
}
cout<<bfs(s,t);
}