AcWing 178. 第K短路

时间:2021-08-11
本文章向大家介绍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;
}

原文地址:https://www.cnblogs.com/ZhengLijie/p/15129028.html