Center of gravity of POJ-1655 balancing act tree

Source: Internet
Author: User

B. exactly match the center of gravity of the tree: Find a vertex, and the largest subtree node in all its Subtrees is the least.

The Code is as follows:

# Include <cstdlib> # include <cstring> # include <cstdio> # include <iostream> # include <algorithm> # define maxn 20000 using namespace STD; // to put it bluntly, this question is to find the center of gravity int N and idx of a tree; // It indicates that there are n nodes. // due to the large number of nodes, the number of nodes is sparse, therefore, the struct node {int X, next, CNT; // CNT is stored in the form of an adjacent table to indicate that the node connected to this edge is the total number of nodes in the subtree bool vis ;} E [(maxn <1) + 5]; // int head [maxn + 5] caused by bidirectional edges; void addedge (int A, int B) {++ idx; E [idx]. vis = false, E [idx]. CNT = 0; E [idx]. X = B, E [idx ]. Next = head [a]; head [a] = idx;} int DFS (int x) {// obtain the number of nodes in the subtree connected by an edge (the entrance edge is not calculated; otherwise, all nodes are N) int sum = 0; for (INT I = head [X]; I! =-1; I = E [I]. Next) {If (! E [I]. vis) {// if this edge has not been accessed E [I]. vis = E [I ^ 1]. vis = true; E [I]. CNT + = DFS (E [I]. x); e [I ^ 1]. CNT = n-e [I]. CNT;} sum + = E [I]. CNT;} return sum + 1;} void solve (Int & X, Int & Y) {Y = 0x7fffffff; For (INT I = 1; I <= N; ++ I) {int max = 0x7fffffff + 1; for (int K = head [I]; k! =-1; k = E [K]. next) {max = max (max, E [K]. CNT) ;}if (max <Y) {Y = max; X = I ;}} int main () {int t; scanf ("% d ", & T); While (t --) {int A, B, X, Y; memset (Head, 0xff, sizeof (head); idx =-1; scanf ("% d", & N); For (INT I = 1; I <n; ++ I) {scanf ("% d", &, & B); addedge (a, B); addedge (B, A);} DFS (1); solve (x, y ); printf ("% d \ n", x, y);} return 0 ;}

 

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.