Language:DefaultBalancing ACT
Time Limit: 1000MS |
|
Memory Limit: 65536K |
Total Submissions: 9418 |
|
Accepted: 3941 |
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
Source POJ monthly--2004.05.15 IOI 2003 Sample Task
|
Code
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include < cmath> #include <queue> #include <stack> #include <vector> #include <set> #include <map > #define L (x) (x<<1) #define R (x) (x<<1|1) #define MID (x, y) ((x+y) >>1) #define EPS 1e-8typedef __ Int64 ll;using namespace std; #define N 20005int num[n],dp[n];int head[n],k;int n;struct stud{int to,next;} e[n*2];inline void Add (int u,int v) {e[k].to=v;e[k].next=head[u];head[u]=k++;} void Dfs (int x,int pre) {dp[x]=0; Num[x]=1; int i; for (i=head[x];i!=-1;i=e[i].next) {int to=e[i].to;if (to==pre) Continue;dfs (to,x);DP [X]=max (Dp[x],num[to]); num[x]+= Num[to];} Dp[x]=max (Dp[x],n-num[x]); For example, the tree is 1 2 3 4 5, without this step dp[5] is 0}int main () {int i,j,t;scanf ("%d", &t), while (t--) {K=0;memset (head,-1,sizeof (head)); scanf ("%d", &n), int u,v;for (i=1;i<n;i++) {scanf ("%d%d", &u,&v); add (u,v); add (v,u);} DFS (1,-1); int ans1=1,ans2=dp[1];for (i=2;i<=n;i++) if (Dp[i]<anS2) {ans1=i;ans2=dp[i];} printf ("%d%d\n", ans1,ans2);} return 0;}
Poj1655balancing Act (center of gravity of the tree)