Poj1655
The first DFS calculates the number of nodes for each subtree.
Second DFS request answer
This is the foundation of poj1741 (Code 1741)
The same is true for poj3107. However, all vertices must be output, and STL (large data size) cannot be used.
# Include <iostream> # include <cstdio> # include <cstring> # include <vector> using namespace STD; int N; vector <int> son [20010]; // graph storage structure int vis [20010]; // indicates whether int num [20010] has been accessed; // The number of subtree nodes int DP [20010]; // Answer void dfs_num (int n) {int Len = Son [N]. size (); num [N] = 1; vis [N] = 1; for (INT I = 0; I <Len; I ++) {int K = Son [N] [I]; // son if (vis [k]) continue; dfs_num (k ); num [N] + = num [k];} // printf ("@ % d \ n", N, num [N]);} void dfs_node (int n, int from) {int K, Len = Son [N]. size (); vis [N] = 1; DP [N] = 0; For (INT I = 0; I <Len; I ++) {k = Son [N] [I]; If (vis [k]) {DP [N] = max (DP [N], n-num [N]);} else {DP [N] = max (DP [N], num [k]); dfs_node (k, n) ;}} int main () {int I, j, k, T, U, V; scanf ("% d", & T); While (t --) {scanf ("% d", & N ); for (I = 1; I <= N; I ++) Son [I]. clear (); memset (Num, 0, sizeof (Num); memset (DP, 0, sizeof (DP); for (I = 1; I <= N-1; I ++) {scanf ("% d", & U, & V); son [u]. push_back (V); son [v]. push_back (U);} memset (VIS, 0, sizeof (VIS); dfs_num (1); memset (VIS, 0, sizeof (VIS); dfs_node (1, -1); for (I = J = k = N; I> = 1; I --) {If (k> DP [I]) {k = DP [I]; j = I;} If (k = DP [I]) {J = I ;}} printf ("% d \ n", j, k );} return 0;}/* 272 61 21 44 53 73 1111 21 31 42 52 64 74 84 98 108 11 */