视频链接
https://www.bilibili.com/video/BV19k4y1K7gV
题目链接
题面
代码
#include <bits/stdc++.h>
#define pii pair<int, int>
#define all(sbe) sbe.begin(),sbe.end()
// #define int long long
using namespace std;
typedef long long ll;
const int N = 1010, M = 20010;
int h[N], rh[N], e[M], ne[M], w[M], idx;
int dist[N];
void add(int he[], int a, int b, int c) {
e[idx] = b, w[idx] = c, ne[idx] = he[a], he[a] = idx ++;
}
signed main(){
#ifdef LOCAL
freopen("in.txt", "r", stdin);
#endif
memset(h, -1, sizeof(h));
memset(rh, -1, sizeof(rh));
int n, m, S, T, K; cin >> n >> m;
for(int i = 1; i <= m; i++) {
int a, b, c; cin >> a >> b >> c;
add(h, a, b, c); add(rh, b, a, c);
// 第二个add建反向图求估价函数 这里使用dijkstra求出估价函数值等于真实值
}
cin >> S >> T >> K;
if(S == T) K ++; // 起点与终点重合求第K+1短路
if(m == 0) {
cout << "-1\n";
return 0;
}
function<void()> dijkstra = [&](){
memset(dist, 0x3f, sizeof(dist));
dist[T] = 0;
vector<bool> vis(N, false);
priority_queue<pii> pq;
pq.push({0, T});
while(pq.size()) {
auto t = pq.top().second; pq.pop();
if(vis[t]) continue;
vis[t] = 1;
for(int i = rh[t]; i != -1; i = ne[i]) {
int j = e[i];
if(dist[j] > dist[t] + w[i]) {
dist[j] = dist[t] + w[i];
pq.push({-dist[j], j});
}
}
}
};
function<void()> bfs = [&](){
vector<int> con(N, 0);
using tp3 = tuple<int, int, int>;
priority_queue<tp3, vector<tp3>, greater<tp3>> pq;
pq.push({dist[S], 0, S});
while(pq.size()) {
auto [x, y, z] = pq.top(); pq.pop();
con[z] ++;
if(con[T] == K) {
cout << y << '\n';
return ;
}
for(int i = h[z]; i != -1; i = ne[i]) {
int j = e[i];
if(con[j] < K) {
pq.push({y + w[i] + dist[j], y + w[i], j});
}
}
}
cout << "-1\n";
return ;
};
dijkstra();
bfs();
return 0;
}