Problem Description
You have a directed weighted graph with n vertexes and m edges. The value of a path is the sum of the weight of the edges you passed. Note that you can pass any edge any times and every time you pass it you will gain the weight.
Now there are q queries that you need to answer. Each of the queries is about the k-th minimum value of all the paths.
Input
The input consists of multiple test cases, starting with an integer t (1≤t≤100), denoting the number of the test cases.
The first line of each test case contains three positive integers n,m,q. (1≤n,m,q≤5∗104)
Each of the next m lines contains three integers ui,vi,wi, indicating that the i−th edge is from ui to vi and weighted wi.(1≤ui,vi≤n,1≤wi≤109)
Each of the next q lines contains one integer k as mentioned above.(1≤k≤5∗104)
It’s guaranteed that Σn ,Σm, Σq,Σmax(k)≤2.5∗105 and max(k) won’t exceed the number of paths in the graph.
Output
For each query, print one integer indicates the answer in line.
Sample Input
1
2 2 2
1 2 1
2 1 2
3
4
Sample Output
3
3
Hint
1->2 value :1
2->1 value: 2
1-> 2-> 1 value: 3
2-> 1-> 2 value: 3
题意:
给出一张有向图,q次询问,每次询问要求输出图上第k短的路径长度(任意起点终点)。
(有向图u到v和v到u是不一样的,而且图中可能有环)
分析:
先把每条边以(u,v,w)形式放进堆,堆按路径权值从小到大排序,然后每次取出堆顶(权值小的),用v的出边扩展新的路径。
但是点v的出度可能会非常大,
如果将所有出边都加入堆中,可能会爆内存
其实将出边排序之后,每次只需要扩展当前点v最小的出边,
和扩展u下一条边即可。
堆中存放结构体
结构体需要记录当前结点u,当前边权总和len,当前最后一条边是u的第几条边(用id记录)
code:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
const int maxm=5e4+10;
struct Node{
int len;//边权和
int u;//最后一条边的入口节点(u,v)中的u
int id;//用到的边id
Node(){};
Node(int a,int b,int c){
len=a,u=b,id=c;
}
bool operator<(const Node &a)const{
return len>a.len;
}
};
int query[maxm],ans[maxm];
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int T;
cin>>T;
while(T--){
int n,m,q;
vector<pair<int,int> >g[maxm];
memset(ans,0,sizeof ans);
cin>>n>>m>>q;
for(int i=0,a,b,c;i<m;i++){
cin>>a>>b>>c;
g[a].push_back({c,b});
}
for(int i=1;i<=n;i++){
sort(g[i].begin(),g[i].end());//按边权从小到大排序
}
int ma=0;
for(int i=0;i<q;i++){
cin>>query[i];
ma=max(ma,query[i]);
}
priority_queue<Node>que;
for(int i=1;i<=n;i++){
if(g[i].size())que.push(Node(g[i][0].first,i,0));//最小边进堆
}
int cnt=0;
while(!que.empty()){
Node x=que.top();
que.pop();
int u=x.u;
int id=x.id;
int len=x.len;
ans[++cnt]=len;//添加至答案列表
if(cnt>=ma)break;//如果数量够了就退出
if(id<(int)g[u].size()-1){//拓展入口节点的其他边
que.push(Node(len-g[u][id].first+g[u][id+1].first,u,id+1));
}
int v=g[u][id].second;//出口节点
if(g[v].size()){//出口节点拓展最小边
que.push(Node(len+g[v][0].first,v,0));
}
}
for(int i=0;i<q;i++){
cout<<ans[query[i]]<<endl;
}
}
return 0;
}