#include using namespace std; struct Edge { int t,next; Edge() {} Edge(int a,int b):t(a),next(b) {} }; Edge e[200005]; int head[100005],n; bool vis[100005]; namespace SGT { const int Maxn=5000000; int ch[Maxn][2],size[Maxn],tot; inline int newnode() { tot++; ch[tot][0]=ch[tot][1]=size[tot]=0; return tot; } int update(int l,int r,int p) { int o=newnode(); size[o]++; if (l==r) return o; else { int m=((l+r)>>1); if (m>=p) ch[o][0]=update(l,m,p); else ch[o][1]=update(m+1,r,p); return o; } } int merge(int x,int y) { if (!x) return y; if (!y) return x; size[x]+=size[y]; ch[x][0]=merge(ch[x][0],ch[y][0]); ch[x][1]=merge(ch[x][1],ch[y][1]); return x; } int query(int l,int r,int o,int p) { if (l==r) return 0; else { int m=((l+r)>>1); if (m>=p) return query(l,m,ch[o][0],p)+size[ch[o][1]]; else return query(m+1,r,ch[o][1],p); } } } int root[100005]; namespace SETS { int fa[100005]; void init(int n) { for(int i=1;i<=n;i++) fa[i]=i; } int find_father(int x) { return (fa[x]==x)?x:fa[x]=find_father(fa[x]); } void merge(int x,int y) { x=find_father(x);y=find_father(y); if (x==y) return; fa[x]=y; } } namespace Tree { int fa[100005][20],dep[100005]; void dfs1(int x) { root[x]=SGT::update(1,n,x); for(int i=head[x];i;i=e[i].next) if (e[i].t!=fa[x][0]) { int u=e[i].t; fa[u][0]=x;dep[u]=dep[x]+1; for(int j=1;j<20;j++) fa[u][j]=fa[fa[u][j-1]][j-1]; dfs1(u); } } int lca(int x,int y) { if (dep[x]>i)&1) x=fa[x][i]; if (x==y) return x; for(int i=19;i>=0;i--) if (fa[x][i]!=fa[y][i]) { x=fa[x][i]; y=fa[y][i]; } return fa[x][0]; } int dis(int x,int y) { return dep[x]+dep[y]-2*dep[lca(x,y)]; } void dfs2(int x) { if (vis[x]) return; vis[x]=1; for(int i=head[x];i;i=e[i].next) if (e[i].t!=fa[x][0]) { int u=e[i].t; dfs2(u); root[x]=SGT::merge(root[x],root[u]); SETS::merge(u,x); } } } int query(int x,int y) { int u=SETS::find_father(x),v=SETS::find_father(y); if (u==v) return abs(SGT::query(1,n,root[u],x)-SGT::query(1,n,root[v],y)); else return Tree::dis(u,v)+SGT::query(1,n,root[u],x)+SGT::query(1,n,root[v],y); } int main() { int cases; scanf("%d",&cases); for(;cases;cases--) { memset(head,0,sizeof(head)); memset(vis,0,sizeof(vis)); SGT::tot=0; scanf("%d",&n); for(int i=1;i