Given a tree with n nodes, the remaining branches after deleting a node will certainly have the maximum number of nodes, and the minimum value of the maximum number of branch nodes for all nodes is obtained.
Solution: Tree DP. the first deep search record the total number of child nodes (including the current node) from the current node (including the current node), the first time the pre-processing is calculated, the complexity is O (N ), the second time, we use the first result to find the maximum number of nodes in each branch. There are two kinds of branches: one is the Child Branch, this is the branch from the current node to the Father's Day point (total number of N-dp [cur]), so that you can calculate it again N times.
Test data:
1
7
2 6
1 2
1 4
4 5
3 7
3 1
Code:
[Html]
# Include <stdio. h>
# Include <string. h>
# Include <algorithm>
Using namespace std;
# Deprecision MAX 110000
# Define max (a, B) (a)> (B )? (A) :( B)
Struct node {
Int v;
Node * next;
} * Head [MAX], tree [MAX];
Int n, m, ptr, dp [MAX], ansval, ansi, cnt;
Void Initial (){
Cnt = ptr = 0;
Ansval = ansi = 2147483647;
Memset (dp, 0, sizeof (dp ));
Memset (head, NULL, sizeof (head ));
}
Void AddEdge (int x, int y ){
Tree [ptr]. v = y;
Tree [ptr]. next = head [x], head [x] = & tree [ptr ++];
Tree [ptr]. v = x;
Tree [ptr]. next = head [y], head [y] = & tree [ptr ++];
}
Void Dfs_Ini (int s, int pa ){
Dp [s] = 1;
Node * p = head [s];
While (p! = NULL ){
If (p-> v! = Pa ){
Dfs_Ini (p-> v, s );
Dp [s] + = dp [p-> v];
}
P = p-> next;
}
} Www.2cto.com
Void Dfs_Solve (int son, int pa ){
Int I, j, tp, tot = 0;
Node * p = head [son];
While (p! = NULL ){
If (p-> v! = Pa ){
Dfs_Solve (p-> v, son );
Tp = dp [p-> v];
Tot = max (tot, tp );
}
P = p-> next;
}
If (tot <n-dp [son])
Tot = n-dp [son];
If (tot <ansval)
Ansval = tot, ansi = son;
}
Int main ()
{
Int I, j, k, a, B, t;
Scanf ("% d", & t );
While (t --){
Scanf ("% d", & n );
Initial ();
For (I = 1; I <n; ++ I ){
Scanf ("% d", & a, & B );
AddEdge (a, B );
}
Dfs_Ini (); // the first in-depth search to record the total number of children of the current node
Dfs_Solve (); // update the answer
Printf ("% d \ n", ansi, ansval );
}
}
Author: woshi250hua