第K短路
输入:
2 2
1 2 5
2 1 4
1 2 2
输出:
14
思路:A*算法求K短路的裸题。, g为与起点的距离,h为与终点的距离,因此通过终点出发的dij,得到h函数,再通过正向dij依照f(n)的大小从小到大搜索图,当第k次搜索到终点时即为第k短路。
AC代码:
/*---------------------------------
*File name: A.cpp
*Creation date: 2020-10-22 16:43
*Link:
*-------------------------------*/
#pragma GCC diagnostic error "-std=c++11"
#include<bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define LL long long
#define PII pair<int, int>
using namespace std;
typedef int readType;
const int maxn = 1e3 + 5;
const int maxm = 1e5 + 5;
const int inf = INT_MAX;
const LL Inf = LLONG_MAX;
const LL mod = 1e9 + 7;
inline readType read(){
readType x = 0, y = 1; char c = getchar();
while(c < '0' || c > '9'){if(c == '-') y = -1; c = getchar();}
while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * y;
}
struct Edge{
int v, next, w;
}edge[maxm];
bool vis[maxn];
int head[maxn];
int n, m;
int tot = 0;
int s, t, k;
int dis[maxn];
struct Node{
int w, p;
friend bool operator < (Node x, Node y){
return x.w > y.w;
}
};
inline void Add_Edge(int u, int v, int w){
edge[tot].v = v;
edge[tot].w = w;
edge[tot].next = head[u];
head[u] = tot++;
}
inline void dij(){
priority_queue<Node> q;
q.push((Node){0, t});
memset(dis, 0x3f3f3f3f, sizeof dis);
dis[t] = 0;
while(!q.empty()){
Node cur = q.top(); q.pop();
if(vis[cur.p]) continue;
vis[cur.p] = 1;
for(int i = head[cur.p]; i != -1; i = edge[i].next){
int v = edge[i].v;
int w = edge[i].w;
// printf("dis[%d] = %d dis[%d] = %d w = %d\n",v, dis[v], cur.p, dis[cur.p], w);
if(dis[v] > dis[cur.p] + w){
dis[v] = dis[cur.p] + w;
q.push((Node){dis[v], v});
}
}
}
}
int times[maxn];
inline int A_Start(){
priority_queue<Node> q;
q.push((Node){dis[s], s});
if(s == t) times[s]++;
while(!q.empty()){
Node cur = q.top(); q.pop();
times[cur.p]++;
if(times[t] == k) return cur.w - dis[cur.p];
for(int i = head[cur.p]; ~i; i = edge[i].next){
int v = edge[i].v;
int w = edge[i].w;
if(times[v] != k){
q.push((Node){(w + cur.w - dis[cur.p]) + dis[v], v});
}
}
}
return -1;
}
int main(){
n = read(), m = read();
for(int i = 1; i <= n; ++i) head[i] = -1;
for(int i = 1; i <= m; ++i){
int u = read(), v = read(), w = read();
Add_Edge(u, v, w);
}
s = read(), t = read(), k = read();
dij();
printf("%d\n", A_Start());
return 0;
}