Poj 1655 balancing act tree center of gravity

Source: Internet
Author: User

Give a tree. After removing a vertex, the tree will become a Unicom block. Find the smallest number of blocks formed after which point is removed.


Idea: tree-like DP. Find the size of the Child tree with each node as the root through a deep search. After removing the node, the Child tree will become the child trees of the node, with the remaining parts, find the maximum number of these blocks, that is, remove the ANS at this point, and then update the total ans.

This question is actually the focus of the tree.


Code:


#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#define MAX 20010using namespace std;int cases;int points;int head[MAX],total;int next[MAX << 1],aim[MAX << 1];int p_ans,ans;inline void Initialize();inline void Add(int x,int y);int DFS(int x,int last);int main(){for(cin >> cases;cases; --cases) {scanf("%d",&points);Initialize();for(int x,y,i = 1;i < points; ++i) {scanf("%d%d",&x,&y);Add(x,y),Add(y,x);}DFS(1,0);printf("%d %d\n",p_ans,ans);}return 0;}inline void Initialize(){ans = 0x7f7f7f7f,total = 0;memset(head,0,sizeof(head));}inline void Add(int x,int y){next[++total] = head[x];aim[total] = y;head[x] = total;}int DFS(int x,int last){int max_size = 0,size = 1;for(int i = head[x];i;i = next[i]) {if(aim[i] == last)continue;int temp = DFS(aim[i],x);max_size = max(max_size,temp);size += temp;}max_size = max(max_size,points - size);if(max_size < ans)ans = max_size,p_ans = x;return size;}


Poj 1655 balancing act tree center of gravity

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.