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