2019牛客第四场 J free 分层图最短路

链接:https://ac.nowcoder.com/acm/contest/884/J
来源:牛客网
 

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 524288K,其他语言1048576K
64bit IO Format: %lld

题目描述

Your are given an undirect connected graph.Every edge has a cost to pass.You should choose a path from S to T and you need to pay for all the edges in your path. However, you can choose at most k edges in the graph and change their costs to zero in the beginning. Please answer the minimal total cost you need to pay.

输入描述:

The first line contains five integers n,m,S,T,K.

For each of the following m lines, there are three integers a,b,l, meaning there is an edge that costs l between a and b.

n is the number of nodes and m is the number of edges.

输出描述:

An integer meaning the minimal total cost.

示例1

输入

复制

3 2 1 3 1
1 2 1
2 3 2

输出

复制

1

2019牛客第四场 J free 分层图最短路_第1张图片

题意:无向图中有最多k条路通过时不产生消耗,问s到t的最短路

思路:分层图的一般模型

代码:

#include 

typedef long long ll;
#define pii pair
using namespace std;
const int maxn = 6e6 + 10;
int n, m, s, t, k;
int ver[maxn], edge[maxn], Next[maxn], Head[maxn], tot = 0;
int dis[maxn], vis[maxn];

void add(int x, int y, int z) {
    ver[++tot] = y;
    edge[tot] = z;
    Next[tot] = Head[x];
    Head[x] = tot;
}

void dij() {
    memset(dis, 0x3f, sizeof(dis));
    priority_queue, greater > q;
    dis[s] = 0;
    q.push({dis[s], s});
    while (!q.empty()) {
        int x = q.top().second;
        q.pop();
        if (vis[x]) continue;
        vis[x] = 1;
        for (int i = Head[x]; i; i = Next[i]) {
            int y = ver[i];
            if (dis[y] > dis[x] + edge[i]) {
                dis[y] = dis[x] + edge[i];
                q.push({dis[y], y});
            }
        }
    }
}

int main() {
    scanf("%d%d%d%d%d", &n, &m, &s, &t, &k);
    int u, v, q;
    while (m--) {
        scanf("%d%d%d", &u, &v, &q);
        for (int i = 0; i <= k; i++) {
            add(u + i * n, v + i * n, q);
            add(v + i * n, u + i * n, q);
            if (i != k) {
                add(u + i * n, v + (i + 1) * n, 0);
                add(v + i * n, u + (i + 1) * n, 0);
            }
        }
    }
    dij();
    printf("%d\n", dis[t + k * n]);
    return 0;
}

 

你可能感兴趣的:(ACM)