题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6705
题意:给你一个有向图,让你求出所有的路径中第k短的
官方题解:
先把每条边以(u,v,w) 形式放进堆,堆按路径权值从小到大排序,然后每次取出堆顶,用v的出边扩展 新的路径。但是一个点的出度可能会非常大(如菊花图),可以发现,将出边排序之后,每次只需要扩 展当前点最小的出边,和扩展到当前点的边的下一条边即可。堆中需要记录当前结点,当前距离,上一 节点距离,扩展到当前节点时下一条应该扩展的边。(注意,如果一次性扩展当前点连出去的所有权值 相同的边,是会TLE的,实际上也是没有必要的。)
复杂度 O(k * log(m + k))
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 1e5 + 10;
struct node{
int pre, to, num;
ll d;
bool operator <(const node& a) const{
return d > a.d;
}
};
struct edge{
int to;
ll d;
bool operator <(const edge& a) const{
return d < a.d;
}
};
int k[maxn];
ll ans[maxn];
vector<edge> v[maxn];
int main()
{
int T, n, m, Q, x, y, kk, cnt;
scanf("%d", &T);
while(T--) {
scanf("%d%d%d", &n, &m, &Q);
for(int i = 1; i <= n; i++) v[i].clear();
for(int i = 0; i < m; i++) {
ll w;
scanf("%d%d%lld", &x, &y, &w);
v[x].push_back(edge{y, w});
}
priority_queue<node> q;
for(int i = 1; i <= n; i++) {
sort(v[i].begin(), v[i].end());
if(v[i].size()) {
q.push(node{i, v[i][0].to, 0, v[i][0].d});
}
}
kk = 0, cnt = 0;
for(int i = 1; i <= Q; i++) {
scanf("%d", &k[i]);
kk = max(kk, k[i]);
}
while(!q.empty()) {
node a = q.top();
q.pop();
cnt++;
ans[cnt] = a.d;
if(cnt == kk) break;
if(a.num < v[a.pre].size() - 1)
q.push(node{a.pre, v[a.pre][a.num + 1].to, a.num + 1, a.d - v[a.pre][a.num].d + v[a.pre][a.num + 1].d});
if(v[a.to].size())
q.push(node{a.to, v[a.to][0].to, 0, a.d + v[a.to][0].d});
}
for(int i = 1; i <= Q; i++) {
printf("%lld\n", ans[k[i]]);
}
}
return 0;
}