#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
using ll = long long ;
const int M=1e6+10;
int n,x,dep[M],mx[M],dp[M];///dep深度,mx从该点到达的最深节点位置
vector<int> g[M];
void dfs(int x,int fa){
dep[x]=dep[dp[x]=fa]+1;
mx[x]=x;
for(auto &t:g[x]){
if(t==fa)continue;
dfs(t,x);
if(dep[mx[t]]>dep[mx[x]])mx[x]=mx[t];
}
}
int main()
{
int x;
ios::sync_with_stdio(false);
cin>>n>>x;
bool tmp=0;
if(x==1)tmp=1;
for(int i=1;i<n;i++){
int a,b;
cin>>a>>b;
g[a].push_back(b);
g[b].push_back(a);
}
dfs(1,-1);
int d=1,p=mx[x];
while(1){
x=dp[x],d++;
if(dep[x]<=d)break;
p=mx[x];
}
int ans;
if(tmp)ans=0;
else ans=dep[p]-2;
int pos=dp[p];
dfs(dp[p],-1);
cout<<ans+dep[mx[pos]]-1;
}
https://ac.nowcoder.com/acm/contest/16489/C
原文:https://www.cnblogs.com/qq1415584788/p/14840742.html