Method: Remember that node 1 is the root of the tree and the DFS is used twice. For the first time, find all the children of each node and add its own node count num [I]. The balance value of each node is calculated for the second time, Bal [I], when calculating, compare the num value of all the subnodes of node I (delete it and form a new tree with each of its subnodes as the root) there is also the value of N-num [I] (after I is deleted, its parent node and Its Related nodes also form a new tree), the biggest is Bal [I].
Note: Wa has been written for several times because it has not considered the boundary (n = 2). It is too unskillful to write DFS, and the code capability needs to be improved!
# Include <iostream> # include <cstdio> # include <cstdlib> # include <cstring> # include <cmath> # include <map> # include <set> # include <vector> # include <algorithm> # include <stack> # include <queue> using namespace STD; # define INF 1000000000 # define EPS 1e-8 # define PII pair <int, int> # define ll long intint t, n, a, B, ans_ I, ans; vector <int> V [20005]; int num [20005], Bal [20005]; int dfs1 (int I, int FA); void dfs2 (int I, int FA ); int m Ain () {// freopen ("in2.txt", "r", stdin); // freopen ("out.txt", "W", stdout ); scanf ("% d", & T); While (t --) {ans_ I = 0; ans = inf; scanf ("% d", & N ); if (n = 1) {printf ("1 0 \ n");} else if (n = 2) {scanf ("% d", &, & B); printf ("1 1 \ n");} else {for (INT I = 1; I <= N; I ++) {v [I]. clear (); num [I] = 1; BAL [I] =-1 ;}for (INT I = 1; I <n; I ++) {scanf ("% d", & A, & B); V [A]. push_back (B); V [B]. push_back (a);} dfs1 (1,-1); dfs2 (1,-1 ); For (INT I = 1; I <= N; I ++) {If (BAL [I] <ans) {ans_ I = I; ans = Bal [I];} printf ("% d \ n", ans_ I, ANS) ;}// fclose (stdin); // fclose (stdout); Return 0 ;} int dfs1 (int I, int FA) {/* If (V [I]. size () = 1) return num [I]; * // This sentence cannot be added. If it is added, it is wa. The reason is very subtle: the reason is that when a leaf node is encountered, its num returns 1 directly, and the size of the leaf node is 1 (only the parent node ). However, I ignore a special case here, that is, the size of the root node of the number of workers may also be 1 !!! So in this case, WA. In fact, there is no need to add this sentence. The following loop statement can process each node well. * // Here we can summarize the nature of a tree: A leaf node must contain an edge, and the root node may contain an edge. Other nodes must contain at least two sides. For (unsigned Int J = 0; j <V [I]. size (); j ++) {Int & t = V [I] [J]; If (t = FA) {continue ;} else {num [I] + = dfs1 (t, I) ;}// cout <I <"_-_" <num [I] <Endl; return num [I];} void dfs2 (int I, int FA) {for (unsigned Int J = 0; j <V [I]. size (); j ++) {Int & t = V [I] [J]; If (t = FA) {Bal [I] = max (BAL [I], num [1]-num [I]);} else {Bal [I] = max (BAL [I], num [T]); dfs2 (t, I) ;}// cout <I <"___" <Bal [I] <Endl ;}