Question:
The center of gravity of the tree is required. The center of gravity is defined to delete this point so that the forest can be balanced as much as possible.
You can also set the number of sub-trees to less than nlogn during sub-tree splitting.
Train of Thought Analysis:
Son [x] indicates that the number of child trees of X does not include itself.
Balance indicates the maximum number of forest nodes.
Finally, we need to minimize the maximum balance.
Balance = max (balance, n-1-son [X], son [J] + 1 )..
# Include <cstdio> # include <iostream> # include <algorithm> # include <cstring> # define maxn 20005 # define INF 0x3f3f3fusing namespace STD; int tot; int to [maxn <1]; int next [maxn <1]; int head [maxn]; int son [maxn]; int N; void Init () {tot = 0; memset (Head, 0, sizeof head);} void addedge (int u, int v) {tot ++; next [tot] = head [u]; to [tot] = V; head [u] = tot;} bool vis [maxn]; int ans, ansize; void DFS (INT now) // calculate the center of gravity of the tree {son [now] = 0; int balance = 0; For (int p = head [now]; P = next [p]) {int v = to [p]; If (vis [v]) continue; vis [v] = true; DFS (v ); son [now] + = Son [v] + 1; balance = max (balance, son [v] + 1);} balance = max (balance, n-1-son [now]); if (balance <ansize | balance = ansize & now <ans) {ans = now, ansize = balance ;}} int main () {int T; scanf ("% d", & T); While (t --) {Init (); scanf ("% d", & N); For (INT I = 2; I <= N; I ++) {int S, E; scanf ("% d", & S, & E); addedge (S, e ); addedge (E, S);} memset (VIS, false, sizeof vis); ansize = inf; vis [1] = true; DFS (1 ); printf ("% d \ n", ANS, ansize);} return 0 ;}
Poj 1655 balancing act (center of gravity of the tree)