ACM-ICPC 2018 南京赛区网络预赛 L. Magical Girl Haze 最短路+分层图

时间:2022-03-14 04:02:11

类似题解

There are NN cities in the country, and MM directional roads from uu to v(1\le u, v\le n)v(1≤u,v≤n). Every road has a distance c_ici​. Haze is a Magical Girl that lives in City 11, she can choose no more than KK roads and make their distances become 00. Now she wants to go to City NN, please help her calculate the minimum distance.

Input

The first line has one integer T(1 \le T\le 5)T(1≤T≤5), then following TT cases.

For each test case, the first line has three integers N, MN,M and KK.

Then the following MM lines each line has three integers, describe a road, U_i, V_i, C_iUi​,Vi​,Ci​. There might be multiple edges between uu and vv.

It is guaranteed that N \le 100000, M \le 200000, K \le 10N≤100000,M≤200000,K≤10,
0 \le C_i \le 1e90≤Ci​≤1e9. There is at least one path between City 11 and City NN.

Output

For each test case, print the minimum distance.

样例输入复制

1
5 6 1
1 2 2
1 3 4
2 4 3
3 4 1
3 5 6
4 5 2

样例输出复制

3
还是一个最短路 只是可以将其中的k条路 权值变为0,那么就可以 用一个d[maxn][K] 跑K次最短路 就能得到结果了,算法思路并不复杂
在此认识了 链式前向星,以及 爆int 之类的 问题,另外本题 卡Vector,所以不得不用 前向星
#include <bits/stdc++.h>
using namespace std; typedef long long ll;
typedef pair<ll,int> pli;
const int N = +;
const int M = +; int n,m,k,tot,head[N];
ll d[N][];bool vis[N][]; struct node {
int to,nex,val;
}mp[M]; void init() {
tot = ;
memset(head,,sizeof(head));
memset(vis,,sizeof(vis));
} void addedge(int u,int v,int val) {
tot++;
mp[tot].to = v;
mp[tot].nex = head[u];
mp[tot].val = val;
head[u] = tot;
} void solve() {
priority_queue<pli, vector<pli>, greater<pli> > que;
//while(que.size()) que.pop();
memset(d,0x3f,sizeof(d));
d[][] = ; que.push(pli(, ));
while (!que.empty()) {
int u = que.top().second;
ll dis = que.top().first;
int level = u/(n+); u %= (n+);
que.pop();
if(vis[u][level]) continue;
vis[u][level] = ;
for(int i=head[u]; i; i=mp[i].nex) {
int v = mp[i].to;
if(dis + mp[i].val <= d[v][level]) {
d[v][level] = dis + mp[i].val;
que.push({d[v][level], level*(n+)+v});
}
if(level==k) continue;
if(dis <= d[v][level+]) {
d[v][level+] = dis;
que.push({dis, (level+)*(n+)+ v});
}
}
}
cout << d[n][k] <<endl;
} int main () {
freopen("in.txt","r",stdin);
int T; scanf("%d", &T);
while(T--) {
init();
scanf("%d %d %d", &n, &m, &k);
for(int i=; i<=m; i++) {
int u,v,val;
scanf("%d %d %d", &u,&v,&val);
addedge(u,v,val);
}
solve();
}
return ;
}