树重心裸题。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=20005;
struct graph{
int nxt,to;
}e[N<<1];
int g[N],w[N],siz[N],n,t,cnt;
void adde(int x,int y){
e[++cnt].nxt=g[x];g[x]=cnt;e[cnt].to=y;
}
void dfs(int u){
siz[u]=1;
for(int i=g[u];i;i=e[i].nxt)
if(!siz[e[i].to]){
dfs(e[i].to);
siz[u]+=siz[e[i].to];
w[u]=max(siz[e[i].to],w[u]);
}
w[u]=max(w[u],n-siz[u]);
}
int main(){
scanf("%d",&t);
while(t--){
scanf("%d",&n);
memset(g,0,sizeof(g));cnt=0;
memset(siz,0,sizeof(siz));
memset(w,0,sizeof(w));
for(int i=1,x,y;i<n;++i){
scanf("%d%d",&x,&y);
adde(x,y);adde(y,x);
}
dfs(1);
int ans=n,id=0;
for(int i=1;i<=n;++i)
if(w[i]<ans){
ans=w[i];id=i;
}
printf("%d %d\n",id,ans);
}
return 0;
}