1. 程式人生 > 其它 >AcWing 178. 第K短路

AcWing 178. 第K短路

題意

給定一張 \(N\) 個點(編號 \(1,2…N\)),\(M\) 條邊的有向圖,求從起點 \(S\) 到終點 \(T\) 的第 \(K\) 短路的長度,路徑允許重複經過點或邊。

注意: 每條最短路中至少要包含一條邊。

由於直接\(BFS\)搜尋空間特別大,所以考慮\(A*\)演算法

  1. 以從\(x\)點到終點的最短距離為估價函式,那麼這個可以通過反向求終點到\(x\)的單源最短距離實現。

  2. 當終點\(T\), 第\(K\)次被拓展的時候,就得到了\(S\)\(T\)的第\(K\)短路。

// Problem: 第K短路
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/180/
// Memory Limit: 64 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include <bits/stdc++.h>

using namespace std;

typedef pair<int, int> PII;
typedef pair<int, pair<int, int>> PIII;

const int N = 1010, M = 200010;
int h[N], rh[N], e[M], ne[M], w[M], idx;
int S, T, K, n, m;
int dist[N];
bool st[N];
int cnt[N];

void add(int h[], int a, int b, int c) {
	e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}

void Dijkstra() {
	priority_queue<PII, vector<PII>, greater<PII>> heap;
	memset(dist, 0x3f, sizeof dist);
	dist[T] = 0;
	heap.push({0, T});
	
	while (heap.size()) {
		auto t = heap.top();
		heap.pop();
		
		int ver = t.second;
		
		if (st[ver]) continue;
		st[ver] = true;
		
		for (int i = rh[ver]; i != -1; i = ne[i]) {
			int j = e[i];
			if (dist[j] > dist[ver] + w[i]) {
				dist[j] = dist[ver] + w[i];
				heap.push({dist[j], j});
			}
		}
	}
}

int astar() {
	priority_queue<PIII, vector<PIII>, greater<PIII>> heap;
	heap.push({dist[S], {0, S}});
	
	while (heap.size()) {
		auto t = heap.top();
		heap.pop();
		
		int ver = t.second.second, distance = t.second.first;
		cnt[ver]++;
		if (cnt[T] == K) return distance;
		
		for (int i = h[ver]; i != -1; i = ne[i]) {
			int j = e[i];
			if (cnt[j] < K) {
				heap.push({distance + w[i] + dist[j], {distance + w[i], j}});
			}
		}
	}
	
	return -1;
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	
	cin >> n >> m;
	memset(h, -1, sizeof h);
	memset(rh, -1, sizeof rh);
	for (int i = 0; i < m; i++) {
		int a, b, c;
		cin >> a >> b >> c;
		add(h, a, b, c), add(rh, b, a, c);
	}
	cin >> S >> T >> K;
	if (S == T) K++; //因為最少要經過一條邊,當S, T一個點輸出0,所以我們先K++
	
	Dijkstra();
	
	cout << astar() << endl;
	
    return 0;
}