Poj 1655 balancing act (center of gravity of the tree)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.