题目描述(https://loj.ac/problem/10136)
思路
3个节点a,b,c选择(a,b)(a,c)(b,c)公共祖先深度最大的节点,3个节点的最大距离为每个节点到公共祖先的距离和 / 2;
代码
#include <cstdio>
#include <algorithm>
const int MAX = 5e5 + 5;
int n, m;
int head[MAX], ver[MAX << 1], nt[MAX << 1], ht;
int f[MAX][21], dep[MAX];
int ans, res, dps;
inline int read() {
int s = 0;
char ch = getchar();
while (ch < '0' || ch > '9') ch = getchar();
while (ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
return s;
}
void add(int x, int y) {
nt[++ht] = head[x], head[x] = ht, ver[ht] = y;
}
void dfs_lca(int x, int y) {
dep[x] = dep[y] + 1;
f[x][0] = y;
for (int i = 1; i <= 19; ++i) f[x][i] = f[f[x][i - 1]][i - 1];
for (int i = head[x], j; i; i = nt[i]) {
j = ver[i];
if (j == y) continue;
dfs_lca(j, x);
}
}
int lca(int x, int y) {
if (dep[x] < dep[y]) std::swap(x, y);
for (int i = 19; i >= 0; --i) {
if (dep[f[x][i]] >= dep[y]) {
x = f[x][i];
ans += (1 << i);
}
}
if (x == y) {
if (dps < dep[x]) res = x, dps = dep[x];
return x;
}
for (int i = 19; i >= 0; --i) {
if (f[x][i] != f[y][i]) {
x = f[x][i], y = f[y][i];
ans += 1 << (i + 1);
}
}
ans += 2;
if (dps < dep[f[x][0]]) res = f[x][0], dps = dep[f[x][0]];
return f[x][0];
}
int main() {
n = read(), m = read();
for (int i = 1, a, b; i < n; ++i) {
a = read(), b = read();
add(a, b), add(b, a);
}
dfs_lca(1, 0);
for (int i = 1, a, b, c; i <= m; ++i) {
a = read(), b = read(), c = read(), ans = 0, dps = 0;
int ab = lca(a, b), ac = lca(a, c), bc = lca(b, c);
// printf("lca:%d %d %d
", ab, ac, bc);
printf("%d %d
", res, ans >> 1);
}
return 0;
}