# loj6038「雅礼集训 2017 Day5」远行（lct+树的直径）

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
#define N 300010
inline char gc(){
static char buf[1<<16],*S,*T;
return *S++;
}
int x=0,f=1;char ch=gc();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=gc();}
while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=gc();
return x*f;
}
int n,m,pa[N],fa[N],c[N][2],sz[N],d1[N],d2[N],lastans=0,q[N];
bool rev[N];
inline int find(int x){return pa[x]==x?x:pa[x]=find(pa[x]);}
inline bool isroot(int x){return x!=c[fa[x]][0]&&x!=c[fa[x]][1];}
inline void update(int p){sz[p]=sz[c[p][0]]+sz[c[p][1]]+1;}
inline void pushdown(int p){
if(!rev[p]) return;rev[p]=0;swap(c[p][0],c[p][1]);
rev[c[p][0]]^=1;rev[c[p][1]]^=1;
}
inline void rotate(int x){
int y=fa[x],z=fa[y],l=x==c[y][1],r=l^1;
if(!isroot(y)) c[z][y==c[z][1]]=x;
fa[c[x][r]]=y;fa[y]=x;fa[x]=z;
c[y][l]=c[x][r];c[x][r]=y;update(y);update(x);
}
inline void splay(int x){
int top=0;q[++top]=x;
for(int xx=x;!isroot(xx);xx=fa[xx]) q[++top]=fa[xx];
while(top) pushdown(q[top--]);
while(!isroot(x)){
int y=fa[x],z=fa[y];
if(!isroot(y)){
if(x==c[y][1]^y==c[z][1]) rotate(x);
else rotate(y);
}rotate(x);
}
}
inline void access(int x){
int y=0;while(x){splay(x);c[x][1]=y;update(x);y=x;x=fa[x];}
}
inline void makeroot(int x){
access(x);splay(x);rev[x]^=1;
}
inline int dis(int x,int y){
makeroot(x);access(y);splay(y);return sz[y]-1;
}
makeroot(x);fa[x]=y;int xx=find(x),yy=find(y);
pa[xx]=yy;int x1=d1[xx],y1=d2[xx],x2=d1[yy],y2=d2[yy];
int mx=dis(x2,y2);
int res=dis(x1,y1);if(res>mx) mx=res,d1[yy]=x1,d2[yy]=y1;
res=dis(x1,y2);if(res>mx) mx=res,d1[yy]=x1,d2[yy]=y2;
res=dis(x1,x2);if(res>mx) mx=res,d1[yy]=x1,d2[yy]=x2;
res=dis(y1,x2);if(res>mx) mx=res,d1[yy]=y1,d2[yy]=x2;
res=dis(y1,y2);if(res>mx) mx=res,d1[yy]=y1,d2[yy]=y2;
}
int main(){
//  freopen("a.in","r",stdin);
}