PKU 1655 Balancing Act(树+树的重心)
#include<cstdio> #include<cstring> #include<algorithm> #define maxn 20005 using namespace std; struct Edge { int to; int next; }e[2*maxn]; int t,n,x,y,tot; int head[maxn],num[maxn],balance[maxn]; void Init() { tot=0; memset(head,-1,sizeof(head)); } void Addedge(int u,int v) { e[tot].to=v; e[tot].next=head[u]; head[u]=tot++; } void dfs(int u,int pre) { balance[u]=0,num[u]=1; for(int i=head[u];i!=-1;i=e[i].next){ int v=e[i].to; if(v==pre) continue ; dfs(v,u); balance[u]=max(balance[u],num[v]); num[u]+=num[v]; } balance[u]=max(balance[u],n-num[u]); } int main() { scanf("%d",&t); while(t--){ scanf("%d",&n); Init(); for(int i=1;i<n;i++){ scanf("%d%d",&x,&y); Addedge(x,y); Addedge(y,x); } dfs(1,-1); int pos=1,ans=balance[1]; for(int i=2;i<=n;i++){ if(balance[i]<ans){ pos=i; ans=balance[i]; } } printf("%d %d\n",pos,ans); } }