题目链接
树的直径的计算:任选一点dfs到最远点p,然后从p在dfs到最远点的距离就是树的直径
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<string>
#include<cmath>
#include<queue>
#include<map>
#include<set>
#include<cstdlib>
#include<vector>
using namespace std;
#define cl(a,b) memset(a,b,sizeof(a))
#define LL long long
#define pb push_back
#define gcd __gcd
#define For(i,j,k) for(int i=(j);i<k;i++)
#define lowbit(i) (i&(-i))
#define _(x) printf("%d\n",x)
const int maxn = 3e6+10;
const int inf = 1 << 28;
int n;
vector<int> G[maxn];
int tmp;
int sum;
void dfs(int u,int fa,int dis){
if(sum<dis){
sum = dis;
tmp = u;
}
for(int i=0;i<G[u].size();i++){
int v = G[u][i];
if(v==fa)continue;
dfs(v,u,dis+1);
}
}
int main(){
scanf("%d",&n);
for(int i=0;i<n-1;i++){
int x,y;scanf("%d%d",&x,&y);
G[x].pb(y);G[y].pb(x);
}
sum=0;
dfs(1,-1,0);//cout<<"tmp "<<tmp<<" sum "<<sum<<endl;
sum = 0;
dfs(tmp,-1,0);
printf("%d\n",sum);
return 0;
}