Description
For example, consider the tree:
Deleting node 4 yields two trees whose member nodes are {5} and {1,2,3,6,7}. The larger of these two trees has five nodes, thus the balance of node 4 is five. Deleting node 1 yields a forest of three trees of equal size: {2,6}, {3,7}, and {4,5}. Each of these trees has two nodes, so the balance of node 1 is two.
For each input tree, calculate the node that has the minimum balance. If multiple nodes have equal balance, output the one with the lowest number.
Input
Output
Sample Input
1 7 2 6 1 2 1 4 4 5 3 7 3 1
Sample Output
1 2
//Serene
//紫書p281 樹的重心
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<cmath>
using namespace std;
const int maxn=200000+10,INF=1<<30;
int T,n,ans,size;
int aa;char c;
int read() {
aa=0;c=getchar();
while(c<'0'||c>'9') c=getchar();
while(c>='0'&&c<='9') aa=aa*10+c-'0',c=getchar();
return aa;
}
int to[2*maxn],nxt[2*maxn],fir[maxn],e=0;
void add(int u,int v) {
to[++e]=v;nxt[e]=fir[u];fir[u]=e;
to[++e]=u;nxt[e]=fir[v];fir[v]=e;
}
bool vis[maxn];
int sum[maxn];
void dfs(int pos) {
vis[pos]=1;
sum[pos]=0;
int maxsum=0,x,y;
for(x=fir[pos];x;x=nxt[x]) {
y=to[x];
if(!vis[y]) {
dfs(y);
maxsum=max(maxsum,sum[y]+1);
sum[pos]+=sum[y]+1;
}
}
maxsum=max(maxsum,n-sum[pos]-1);
if(maxsum<size||(maxsum==size&&pos<ans)) {
size=maxsum; ans=pos;
}
}
int main() {
int x,y;
T=read();
while(T--) {
n=read();e=0;size=INF;
memset(nxt,0,sizeof(nxt));
memset(fir,0,sizeof(fir));
memset(vis,0,sizeof(vis));
for(int i=1;i<n;++i) {
x=read();y=read();
add(x,y);
}
dfs(1);
printf("%d %d\n",ans,size);
}
return 0;
}