2019CCPC网络赛 - D. path

题意:

给定一张有 n 个点、m 条边的有向带权图,给 q 次询问,每次询问在图上的第 k 短路径的长度,点和边可反复经过。(n, m, q, k <= 5e4)

链接:

https://cn.vjudge.net/problem/HDU-6705

题解:

考虑离线处理,求出最短到第 max{ki} 短的路径长度。维护一个小顶堆,初始化放入每个点的最短出弧,第 k 次取出得到第 k 短的答案。取出该边(u -> v)后只需选择扩展下一最短出弧(u -> v’),以及往下一层扩展 v 的最短出弧。

参考代码:

#include

using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
#define pb push_back
#define sz(a) ((int)a.size())
#define mem(a, b) memset(a, b, sizeof a)
#define lson (rt << 1)
#define rson (rt << 1 | 1)
#define gmid (l + r >> 1)
const int maxn = 5e4 + 5;
const int maxm = 2e5 + 5;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;

struct Node{
     
	int u, v, k; ll w;
	bool operator < (const Node &o) const {
      return w > o.w; }
};
priority_queue<Node> q;
vector<pii> G[maxn];
ll ans[maxn]; int qr[maxn];
int n, m, qi;

int main() {
     

//    ios::sync_with_stdio(0); cin.tie(0);
	int t; scanf("%d", &t);
	while(t--){
     

		scanf("%d%d%d", &n, &m, &qi);
		for(int i = 1; i <= n; ++i) G[i].clear();
		for(int i = 1; i <= m; ++i){
     

			int u, v, w; scanf("%d%d%d", &u, &v, &w);
			G[u].pb({
     w, v});
		}
		int lim = 0;
		for(int i = 1; i <= qi; ++i){
     

			scanf("%d", &qr[i]);
			lim = max(lim, qr[i]);
		}
		while(!q.empty()) q.pop();
		for(int i = 1; i <= n; ++i){
     

			sort(G[i].begin(), G[i].end());
			if(sz(G[i])) q.push({
     i, G[i][0].second, 0, G[i][0].first});
		}
		for(int i = 1; i <= lim; ++i){
     

			Node tmp = q.top(); q.pop();
			ans[i] = tmp.w;
			if(tmp.k + 1 < sz(G[tmp.u])) q.push({
     tmp.u, G[tmp.u][tmp.k + 1].second, tmp.k + 1, tmp.w - G[tmp.u][tmp.k].first + G[tmp.u][tmp.k + 1].first});
			if(sz(G[tmp.v])) q.push({
     tmp.v, G[tmp.v][0].second, 0, tmp.w + G[tmp.v][0].first});
		}
		for(int i = 1; i <= qi; ++i) printf("%lld\n", ans[qr[i]]);
	}
    return 0;
}

你可能感兴趣的:(2019CCPC网络赛 - D. path)