- How far away ?
1
- @ 2026-7-25 9:42:04
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pii pair<int, int>
void solve() {
int n, m;
cin >> n >> m;
vector e(n + 1, vector<pii>());
for (int i = 1, u, v, w; i < n; i++) {
cin >> u >> v >> w;
e[u].push_back({v, w});
e[v].push_back({u, w});
}
vector<int> dep(n + 1), len(n + 1);
int M = __lg(n);
vector f(n + 1, vector<int>(M + 1));
auto dfs = [&] (auto &&self, int u, int fa)->void {
for (auto [v, w] : e[u]) {
if (v == fa) continue;
dep[v] = dep[u] + 1;
len[v] = len[u] + w;
f[v][0] = u;
self(self, v, u);
}
};
dfs(dfs, 1, 0);
for (int j = 1; j <= M; j++) {
for (int i = 1; i <= n; i++) {
f[i][j] = f[f[i][j - 1]][j - 1];
}
}
auto lca = [&] (int x, int y)->int {
if (dep[x] < dep[y]) swap(x, y);
int len = dep[x] - dep[y];
for (int j = 0; j <= M; j++) {
if (len >> j & 1) {
x = f[x][j];
}
}
assert(dep[x] == dep[y]);
if (x == y) return x;
for (int j = M; j >= 0; j--) {
int nx = f[x][j], ny = f[y][j];
if (nx == ny) continue;
x = nx, y = ny;
}
return f[x][0];
};
while (m--) {
int x, y;
cin >> x >> y;
// cout << " x = " << x << " y = " << y << endl;
int l = lca(x, y);
// cout << "lca = " << l << endl;
cout << len[x] - len[l] + (len[y] - len[l]) << '\n';
}
}
signed main() {
ios::sync_with_stdio(0); cin.tie(0);
int t = 1;
cin >> t;
while (t--) solve();
return 0;
}
/*
g++ -std=c++20 1.cpp -o 1 && 1 < in.txt > out.txt
*/
0 条评论
目前还没有评论...
信息
- ID
- 513
- 时间
- ms
- 内存
- MiB
- 难度
- 5
- 标签
- (无)
- 递交数
- 68
- 已通过
- 27
- 上传者