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

链接

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

题目来源

ACM-ICPC 2018 南京赛区网络预赛

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int MAX = 2e5 + 7;
const ll INF = 0x3f3f3f3f3f3f3f3f;
int cnt, n, m, k;
struct node{
    int x;
    ll y;
    bool operator < (const node &a) const{
        return y > a.y;
    }
};
struct edge{
    int to, c, next;
} e[MAX];
int head[MAX];
void add(int x, int y, int z){
    e[cnt] = {y, z, head[x]};
    head[x] = cnt++;
}
ll dis[MAX][15];
int vis[MAX][15];
void dijkstra(){
    priority_queue <node> q;
    memset(vis, 0, sizeof vis);
    memset(dis, INF, sizeof dis);
    dis[1][0] = 0;
    q.push((node){1, 0});
    while(!q.empty()){
        node x = q.top();
        q.pop();
        int lev = x.x / n;
        int u = x.x % n;
        if(vis[u][lev]) continue;
        vis[u][lev] = 1;
        for(int i = head[u]; i != -1; i = e[i].next){
            int v = e[i].to;
            int c = e[i].c;
            if(dis[u][lev] + c < dis[v][lev]){
                dis[v][lev] = dis[u][lev] + c;
                q.push((node){lev * n + v, dis[v][lev]});
            }
            if(lev == k) continue;
            if(dis[v][lev + 1] > dis[u][lev]){
                dis[v][lev + 1] = dis[u][lev];
                q.push((node){(lev + 1) * n + v, dis[v][lev + 1]});
            }
        }
    }
}
int main(){
    int M;
    for(scanf("%d", &M); M; M--){
        memset(head, -1, sizeof head);
        cnt = 0;
        scanf("%d%d%d", &n, &m, &k);
        for(int i = 0, x, y, z; i < m; i++){
            scanf("%d%d%d", &x, &y, &z);
            add(x, y, z);
        }
        dijkstra();
        printf("%lld\n", dis[n][k]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Head_Hard/article/details/82318473