#include <bits/stdc++.h>
using namespace std;
const int NR = 510000;
int nxt[NR], to[NR], head[NR], wid[NR], tot;
int dep[NR], fa[NR][30], lg[NR];
void add(int x, int y)
{
to[++tot] = y;
nxt[tot] = head[x];
head[x] = tot;
}
void dfs(int now, int fath)
{
fa[now][0] = fath;
dep[now] = dep[fath] + 1;
for (int i = 1; i <= 25; ++i)
fa[now][i] = fa[fa[now][i - 1]][i - 1];
for (int i = head[now]; i; i = nxt[i])
if (to[i] != fath)
dfs(to[i], now);
}
int LCA(int x, int y)
{
int cnt1 = 0, cnt2 = 0;
if (dep[x] > dep[y]) {
while (dep[x] > dep[y]) {
x = fa[x][lg[dep[x] - dep[y]]];
cnt1 += (1 << (lg[dep[x] - dep[y]]));
}
} else {
while (dep[x] < dep[y]) {
y = fa[y][lg[dep[y] - dep[x]]];
cnt2 += (1 << (lg[dep[y] - dep[x]]));
}
}
if (x == y)
return (cnt1 * 2) + cnt2;
for (int k = 25; k >= 0; --k)
if (fa[x][k] != fa[y][k]) {
x = fa[x][k], y = fa[y][k];
cnt1 += (1 << k);
cnt2 += (1 << k);
}
return (cnt1 * 2) + cnt2;
}
int main()
{
int n, ans1 = 0, ans2 = 0, ans3, u, v;
cin >> n;
for (int i = 1; i < n; i++) {
int x, y;
cin >> x >> y;
add(x, y);
add(y, x);
}
lg[0] = 1;
for (int i = 1; i <= n; i++)
lg[i] = lg[i / 2] + 1;
dfs(1, 0);
for (int i = 1; i <= n; i++) {
wid[dep[i]]++;
}
for (int i = 1; i <= n; i++) {
ans1 = max(ans1, dep[i]);
ans2 = max(ans2, wid[i]);
}
cin >> u >> v;
ans3 = LCA(u, v);
cout << ans1 << endl << ans2 << endl << ans3;
return 0;
}
样例过了 但只有30pts #4 #5 #10 AC了,其他都WA王子了