Analysis
这道题的特殊性质非常有引导性,可以从最简单的情况入手。
case 1 :
起点 和终点 相同,且所有 个节点都是关键点。
答案为 ,因为每条边都需要被遍历两次(一去一回)。
case 2 :
所有节点都是关键点,但起点 和终点 不同。
假设以 为起点和终点,按照情况一的方式遍历所有边,总路程为 。但由于实际起点是 ,需要先从 走到 (沿树上的简单路径),因此最终答案为:
其中 表示 到 的简单路径长度。
case 3 : special properties A
仅关键点需要被遍历。
我们设 为所有 个关键点的最小连通块内所有边的边集。因为我们需要遍历所有关键点,所以只需在这个最小的连通块内行走,且从 到 的路径只需走一次。
最终答案为:
default
我们只需要先把 和 移动最小距离到连通块里,这段距离为 。这样就转化为特殊性质 A 了。同样设 为所有 个关键点的最小连通块内所有边的边集。答案为:
这个过程可以使用树上倍增来加速。
Details
构造连通块首先以一个关键点为根,那么一个点属于连通块当且仅当其子树内包含至少一个关键点。这样的话 和 只需要向上跳就一定能进入连通块。
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;
}