洛谷 P2939 [USACO09FEB]改造路Revamping Trails

时间:2019-09-12
本文章向大家介绍洛谷 P2939 [USACO09FEB]改造路Revamping Trails,主要包括洛谷 P2939 [USACO09FEB]改造路Revamping Trails使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

洛谷 P2939 [USACO09FEB]改造路Revamping Trails

Description

  • 约翰一共有N)个牧场.由M条布满尘埃的小径连接.小径可 以双向通行.每天早上约翰从牧场1出发到牧场N去给奶牛检查身体.

    通过每条小径都需要消耗一定的时间.约翰打算升级其中K条小径,使之成为高 速公路.在高速公路上的通行几乎是瞬间完成的,所以高速公路的通行时间为0.

    请帮助约翰决定对哪些小径进行升级,使他每天从1号牧场到第N号牧场所花的时间最短

Input

  • * Line 1: Three space-separated integers: N, M, and K

    * Lines 2..M+1: Line i+1 describes trail i with three space-separated integers: P1_i, P2_i, and T_i

Output

  • Line 1: The length of the shortest path after revamping no more than K edges

Data Size

  • 1 <= N <= 10,000
  • 1 <= M <= 50,000
  • 1 <= T_i <= 1,000,000
  • 1 <= K <= 20

题解:

  • 分层图。
  • 很容易看出吧。其实就是模版。原理是建k + 1图。第一层是原图,第二层是用一次“神力”的图,第三层是用两次“神力”的图… …。建完图后跑最短路即可。
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#define N 10005 * 42
#define M 100005 * 42
using namespace std;

struct Node
{
    int val, pos;
    friend bool operator < (Node x, Node y) {
        return x.val > y.val;
    }
};
priority_queue<Node> que;
struct E {int next, to, dis;} e[M];
int n, m, k, num, ans = 0x7fffffff;
int dis[N], h[N];
bool vis[N];

int read()
{
    int x = 0; char c = getchar();
    while(c < '0' || c > '9') c = getchar();
    while(c >= '0' && c <= '9') {x = x * 10 + c - '0'; c = getchar();}
    return x;
}

void add(int u, int v, int w)
{
    e[++num].next = h[u];
    e[num].to = v;
    e[num].dis = w;
    h[u] = num;
}

int main()
{
    cin >> n >> m >> k;
    for(int i = 1; i <= m; i++)
    {
        int u = read(), v = read(), w = read();
        add(u, v, w), add(v, u, w);
        for(int j = 1; j <= k; j++)
        {
            add(u + j * n, v + j * n, w);
            add(v + j * n, u + j * n, w);
            add(u + (j - 1) * n, v + j * n, 0);
            add(v + (j - 1) * n, u + j * n, 0);
        }
    }
    memset(dis, 0x3f, sizeof(dis));
    dis[1] = 0, que.push((Node){0, 1});
    while(que.size())
    {
        int now = que.top().pos;
        que.pop();
        if(vis[now]) continue;
        vis[now] = 1;
        for(int i = h[now]; i != 0; i = e[i].next)
            if(dis[now] + e[i].dis < dis[e[i].to])
            {
                dis[e[i].to] = dis[now] + e[i].dis;
                que.push((Node){dis[e[i].to], e[i].to});
            }
    }
    for(int i = 0; i <= k; i++) ans = min(ans, dis[n + i * n]);
    cout << ans;
    return 0;
}

原文地址:https://www.cnblogs.com/BigYellowDog/p/11515487.html