Bzoj 1131 poi2008 sta tree DP

Source: Internet
Author: User

Given a rootless tree with N points, you must find a root node to maximize the sum of depth.

Make f [x] the sum of the depths of the subtree rooted in X

First, we can find any node for deep search to calculate the size of each subtree and the sum of the depth of all vertices.

Then, search the node for the root node. The State is transferred from the parent node to the child node. The transfer equation is as follows:


When we change the root node from 4 nodes to 5 nodes, the depth of each vertex in the orange part is + 1, and the depth of each vertex in the green part is-1.

Therefore, the state transition equation is obtained:

F [x] = f [Fa [x] + N-2 * size [x]

Scan the array to obtain the solution.

#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>#define M 1001001using namespace std;typedef long long ll;struct abcd{int to,next;}table[M<<1];int head[M],tot;int n,ans,fa[M],siz[M];ll f[M]; //根节点深度为0 void Add(int x,int y){table[++tot].to=y;table[tot].next=head[x];head[x]=tot;}void DFS1(int x){int i;siz[x]=1;for(i=head[x];i;i=table[i].next){if(table[i].to==fa[x])continue;fa[table[i].to]=x;DFS1(table[i].to);siz[x]+=siz[table[i].to];f[x]+=f[table[i].to]+siz[table[i].to];}}void DFS2(int x){int i;if(x!=1)f[x]=f[fa[x]]+n-siz[x]-siz[x];for(i=head[x];i;i=table[i].next){if(table[i].to==fa[x])continue;DFS2(table[i].to);}}int main(){int i,x,y;cin>>n;for(i=1;i<n;i++){scanf("%d%d",&x,&y);Add(x,y);Add(y,x);}DFS1(1);DFS2(1);for(i=1;i<=n;i++)if(f[i]>f[ans])ans=i;cout<<ans<<endl;}


Bzoj 1131 poi2008 sta tree DP

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.