如题,debug半天查不出来,求调。
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;int fa[maxn];
int siz[maxn],f[maxn],son[maxn],pos1,pos2,n;
bool flag;
vector<int> vec[maxn];
void dfs(int x,int t){
fa[x]=t;
int tmp=0;
siz[x]=1;
son[t]=x;
for(auto to:vec[x]){
if(to==t)continue;
dfs(to,x);
siz[x]+=siz[to];
tmp=max(tmp,siz[to]);
}
tmp=max(tmp,n-siz[x]);
f[x]=tmp;
if(f[x]<f[pos1]) pos1=x,pos2=0;
if(f[x]==f[pos1]) pos2=x;
}
int S;
void dfs2(int x,int f){
if(vec[x].size()==1){
S=x;
return ;
}
for(int y:vec[x]){
if(y==f)continue;
dfs2(y,x);
}
}
int main(){
int T;
cin >> T;
while(T--){
f[0]=INT_MAX;
for(int i=1;i<=n;i++){
siz[i]=0;
f[i]=0;
fa[i]=0;
vec[i].clear();
}
cin >> n;int x,y;
for(int i=1;i<n;i++){
cin >> x >> y;
vec[x].push_back(y);
vec[y].push_back(x);
}
dfs(1,0);
//cout << pos1<<' '<<pos2 << endl;
if(pos2==0||pos2==pos1){
cout << x << ' ' << y << endl;
cout << x << ' ' << y << endl;
continue;
}
else{
if(fa[pos1]!=pos2)swap(pos1,pos2);
dfs2(pos1,pos2);
printf("%d %d\n%d %d\n",S,fa[S],S,pos2);
}
}
}