原题传送门
分别以
为起点遍历一遍求出树上各点与
的距离
希望久一点,
希望快一点
那么枚举点
,若
,说明之前
肯定被
抓到了
所以对于所有的
,答案是
Code:
#include <bits/stdc++.h>
#define maxn 200010
using namespace std;
struct Edge{
int to, next;
}edge[maxn << 1];
int num, head[maxn], f[maxn][2], n, a, b;
inline int read(){
int s = 0, w = 1;
char c = getchar();
for (; !isdigit(c); c = getchar()) if (c == '-') w = -1;
for (; isdigit(c); c = getchar()) s = (s << 1) + (s << 3) + (c ^ 48);
return s * w;
}
void addedge(int x, int y){ edge[++num] = (Edge){y, head[x]}, head[x] = num; }
void dfs(int u, int pre, int s, int opt){
f[u][opt] = s;
for (int i = head[u]; i; i = edge[i].next){
int v = edge[i].to;
if (v != pre) dfs(v, u, s + 1, opt);
}
}
int main(){
n = read(), b = read(), a = 1;
for (int i = 1; i < n; ++i){
int x = read(), y = read();
addedge(x, y), addedge(y, x);
}
dfs(1, 0, 0, 1);
dfs(b, 0, 0, 2);
int ans = 0;
for (int i = 2; i <= n; ++i)
if (f[i][2] < f[i][1]) ans = max(ans, f[i][1]);
printf("%d\n", ans << 1);
return 0;
}