P9433 [NAPC-#1] Stage5 - Conveyors

· · 题解

Analysis

这道题的特殊性质非常有引导性,可以从最简单的情况入手。

case 1 :s = t, k = n

起点 s 和终点 t 相同,且所有 n 个节点都是关键点。

答案为 2 \times \sum_{i=1}^{n-1} w_i,因为每条边都需要被遍历两次(一去一回)。

case 2 :k = n

所有节点都是关键点,但起点 s 和终点 t 不同。

假设以 t 为起点和终点,按照情况一的方式遍历所有边,总路程为 2 \times \sum_{i=1}^{n-1} w_i。但由于实际起点是 s,需要先从 t 走到 s(沿树上的简单路径),因此最终答案为:

2 \times \sum_{i = 1}^{n - 1}w_i - \text{dist}(s,t)

其中 \text{dist}(s, t) 表示 s 到 t 的简单路径长度。

case 3 : special properties A

仅关键点需要被遍历。

我们设 E 为所有 k 个关键点的最小连通块内所有边的边集。因为我们需要遍历所有关键点,所以只需在这个最小的连通块内行走,且从 s 到 t 的路径只需走一次。

最终答案为:

2 \times \sum_{i \in E}w_i - \text{dist}(s,t)

default

我们只需要先把 s 和 t 移动最小距离到连通块里,这段距离为 extra_w。这样就转化为特殊性质 A 了。同样设 E 为所有 k 个关键点的最小连通块内所有边的边集。答案为:

2 \times \sum_{i \in E}w_i - \text{dist}(s,t) - extra_w

这个过程可以使用树上倍增来加速。

Details

构造连通块首先以一个关键点为根,那么一个点属于连通块当且仅当其子树内包含至少一个关键点。这样的话 s 和 t 只需要向上跳就一定能进入连通块。

Code

#include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>
#include <utility>

using pii = std::pair <int, int>;
const int MAXN = 1e5 + 10;


int n, q, k, allw, root;
int dep[MAXN], up[MAXN][25], in[MAXN], sum[MAXN];

std::vector <pii> g[MAXN];

void dfs (int u, int fa) {
    dep[u] = dep[fa] + 1;
    up[u][0] = fa;

    for (auto t : g[u]) {
        int v = t.first, w = t.second;
        if (v == fa) continue;
        sum[v] = sum[u] + w;
        dfs(v, u);
        if (in[v])
            in[u] = 1, allw += w;
    }
}

int lca (int a, int b) {
    if (dep[a] < dep[b])
        std::swap(a, b);

    for (int i = 20; i >= 0; i--)
        if (dep[up[a][i]] >= dep[b])
            a = up[a][i];

    if (a == b) return a;

    for (int i = 20; i >= 0; i--)
        if (up[a][i] != up[b][i])
            a = up[a][i], b = up[b][i];

    return up[a][0];
}

int getdist (int u, int v) {
    int l = lca(u, v);
    return sum[u] + sum[v] - 2 * sum[l];
}

void solve () {
    int s, t; std::cin >> s >> t;
    int ans = 0;

    for (int i = 20; i >= 0; i--)
        if (up[s][i] && !in[up[s][i]])
            ans += sum[s] - sum[up[s][i]], s = up[s][i];
    if (!in[s])
        ans += sum[s] - sum[up[s][0]], s = up[s][0];

    for (int i = 20; i >= 0; i--)
        if (up[t][i] && !in[up[t][i]])
            ans += sum[t] - sum[up[t][i]], t = up[t][i];
    if (!in[t])
        ans += sum[t] - sum[up[t][0]], t = up[t][0];

    ans += allw * 2;
    ans -= getdist(s, t);

    std::cout << ans << '\n';
}

int main () {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::cout.tie(nullptr);

    std::cin >> n >> q >> k;

    for (int i = 1; i < n; i++) {
        int u, v, w; std::cin >> u >> v >> w;
        g[u].push_back({v, w});
        g[v].push_back({u, w});
    }

    for (int i = 1; i <= k; i++) {
        int x; std::cin >> x;
        in[x] = 1;
        root = x;
    }

    dfs(root, 0);

    for (int i = 1; i <= 20; i++)
        for (int j = 1; j <= n; j++)
            up[j][i] = up[up[j][i - 1]][i - 1];

    while (q--) {
        solve();
    }

    return 0;
}