There is a tree with N nodes. The Balancing of each node is the maximum number of nodes in the subtree after the node is deleted. Ask the minimum Balancing value and the node number. If Balancing is the same, the number of the output node is smaller.
Code:
[Cpp]
# Include <stdio. h>
# Include <string. h>
# Define maxn20005
Struct Edge {
Int v;
Int next;
} Edge [MAXN * 2];
Int sum [MAXN * 2], son [MAXN];
/*
Sum [] records the total number of nodes except the "parent node subtree"
Son [] records the maximum number of node points in all subtree except "parent node subtree"
The parent node is understood as the last node in the DFS process.
*/
Int head [MAXN], visited [MAXN];
Int tot;
Int Max (int a, int B)
{
Return a> B? A: B;
}
Void addedge (int x, int y)
{
Tot ++;
Edge [tot]. v = y;
Edge [tot]. next = head [x];
Head [x] = tot;
Tot ++;
Edge [tot]. v = x;
Edge [tot]. next = head [y];
Head [y] = tot;
}
Void dfs (int x)
{
Visited [x] = 1;
Int t;
For (t = head [x]; t! =-1; t = edge [t]. next)
{
If (! Visited [edge [t]. v])
{
Dfs (edge [t]. v );
Sum [x] + = sum [edge [t]. v];
If (son [x] <sum [edge [t]. v])
Son [x] = sum [edge [t]. v];
}
}
}
Int main ()
{
Int ncase;
Scanf ("% d", & ncase );
While (ncase --)
{
Int I, N;
Int x, y;
Int id, ans;
Scanf ("% d", & N );
Tot = 0;
Memset (head,-1, sizeof (head ));
Memset (edge, 0, sizeof (edge ));
For (I = 1; I <N; I ++)
{
Scanf ("% d", & x, & y );
Addedge (x, y );
}
Memset (visited, 0, sizeof (visited ));
Memset (son, 0, sizeof (son ));
For (I = 0; I <= N; I ++)
Sum [I] = 1;
Dfs (1 );
Id = 1;
Ans = son [1]; www.2cto.com
For (I = 2; I <N; I ++)
If (ans> Max (son [I], sum [1]-sum [I]) // sum [1] indicates the number of nodes in the entire tree, sum [1]-sum [I] indicates the number of nodes in the parent node subtree.
{
Ans = Max (son [I], sum [1]-sum [I]);
Id = I;
}
Printf ("% d \ n", id, ans );
}
Return 0;
}