Balancing ACT
Time Limit: 1000MS |
|
Memory Limit: 65536K |
Total Submissions: 9913 |
|
Accepted: 4069 |
Description
Consider a tree T with N (1 <= n <= 20,000) nodes numbered 1...N. Deleting all node from the tree yields a forest:a Collection of one or more trees. Define the balance of a node to being the size of the largest tree in the forest t created by deleting that node from T.
For example, consider the tree:
Deleting node 4 yields-trees whose member nodes is {5} and {1,2,3,6,7}. The larger of these and trees have 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 the these trees has a nodes, so the balance of node 1 is a.
For each input tree, calculate the node, the minimum balance. If multiple nodes has equal balance, output the one with the lowest number.
Input
The first line of input contains a single integer t (1 <= t <=), the number of test cases. The first line of all test case contains an integer n (1 <= n <= 20,000), the number of congruence. The next N-1 lines each contains and space-separated node numbers that is the endpoints of an edge in the tree. No Edge would be listed twice, and all edges would be listed.
Output
For each test case, print a line containing-integers, the number of the node with minimum balance and the balance of T Hat node.
Sample Input
172 61 21 44 53 73 1
Sample Output
1 2
#include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include < algorithm> #include <queue> #include <vector>using namespace std; #define LL Long Long#define N 21000# Define MEM (a,t) memset (A,t,sizeof (a)) const int inf=1000005;int cnt,n;struct node{int v,next;} E[n*2];int head[n];int num[n];int ans,index;void Add (int u,int v) {e[cnt].v=v; E[cnt].next=head[u]; head[u]=cnt++;} void Dfs (int u,int len,int fa) {int i,v,tmp=0; Num[u]=1; for (I=head[u];i!=-1;i=e[i].next) {v=e[i].v; if (V!=FA) {DFS (v,len+1,u); Tmp=max (Tmp,num[v]); NUM[U]+=NUM[V]; }} int T=max (Tmp,n-num[u]); if (T<=ans) {if (u<index| | T<ans) {ans=t; Index=u; }}}int Main () {//freopen ("In.txt", "R", stdin); int i,u,v,t; scanf ("%d", &t); while (t--) {scanf ("%d", &n); cnt=0; MEM (head,-1); for (i=1;i<n;i++) {scanf ("%d%d", &u,&v); Add (U,V); Add (V,u); } mem (num,0); Ans=n; DFS (1,0,-1); printf ("%d%d\n", Index,ans); } return 0;}
POJ 1655 Balancing Act (center of gravity of the tree)