给定一张 N 个点(编号 1,2…N),M 条边的有向图,求从起点 S 到终点 T 的第 K 短路的长度,路径允许重复经过点或边。
注意: 每条最短路中至少要包含一条边。
输入格式
第一行包含两个整数 N 和 M。
接下来 M 行,每行包含三个整数 A,B 和 L,表示点 A 与点 B 之间存在有向边,且边长为 L。
最后一行包含三个整数 S,T 和 K,分别表示起点 S,终点 T 和第 K 短路。
输出格式
输出占一行,包含一个整数,表示第 K 短路的长度,如果第 K 短路不存在,则输出 −1。
数据范围
1≤S,T≤N≤1000,
0≤M≤105,
1≤K≤1000,
1≤L≤100
输入样例:
2 2
1 2 5
2 1 4
1 2 2
输出样例:
14
主要思路:
主要是要构造估价函数
f(x)=g(x)+h(x) 当前代价+预估代价
其越小,路越短。
所以反向建图,跑一遍最短路即可得到各个点到终点的最短距离(即为h(x) )
第k次过终点时的dis即为第k短路。
!注意可能存在起点与终点相同的情况,从起点出发不算来到了终点,故若s==t,k++.
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
const int N=1e5+10;
typedef pair<int,int> pa;
vector<int> loc[N],w[N],rl[N],rw[N];
int dis[N];
int n,m;
int s,t,k;
struct node
{
int g,h,l;
bool operator<(node a)const{
return a.g+a.h<g+h;
}
};
void dijkstra()
{
bool book[N]={0};
priority_queue<pa,vector<pa> ,greater<pa> > q;
memset(dis,0x3f, sizeof(dis));
dis[t]=0;
q.push({0,t});
while(q.size())
{
pa now=q.top();
q.pop();
int l=now.second,diss=now.first;
if(book[l]) continue;
book[l]=1;
for(int i=0;i<rl[l].size();i++)
{
int ll=rl[l][i],disss=rw[l][i];
if(dis[ll]>diss+disss)
{
dis[ll]=diss+disss;
q.push({dis[ll],ll});
}
}
}
}
int a_strat()
{
priority_queue<node> q;
int times[N]={0};
if(dis[s]>=0x3f3f3f3f) return -1;
node x;
x.l=s,x.g=0,x.h=dis[s];
q.push(x);
if(s==t)
k++;//防止出现起点终点相同时上来就访问一次,所以直接给k加一
while(q.size())
{
node now=q.top();
q.pop();
int l=now.l,diss=now.g;
times[l]++;
if(times[t]==k) return diss;
if(times[l]>k) continue;
for(int i=0;i<loc[l].size();i++)
{
node x;
x.l=loc[l][i];
x.h=dis[x.l];
x.g=diss+w[l][i];
q.push(x);
}
}
return -1;
}
int main()
{
cin>>n>>m;
while(m--)
{
int x,y,z;
cin>>x>>y>>z;
loc[x].push_back(y);
w[x].push_back(z);
rl[y].push_back(x);
rw[y].push_back(z);
}
cin>>s>>t>>k;
dijkstra();
cout<<a_strat()<<endl;
return 0;
}