这个题很水,很明显树形dp。
dfs处理出来子树大小size,
然后dp出来向下的深度和down,
然后再dp向上的深度和up,
然后遍历一遍取max就好了。
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstdlib>
#define ll long long
using namespace std;
inline int read(){
int x=0;char ch=' ';int f=1;
while(ch!='-'&&(ch<'0'||ch>'9'))ch=getchar();
if(ch=='-')f=-1,ch=getchar();
while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
return x*f;
}
struct edge{
int to,next;
}e[2000001];
int n,tot;
int head[1000001];
inline void addedge(int x,int y){
e[++tot].to=y;e[tot].next=head[x];head[x]=tot;
}
ll up[1000001];
ll down[1000001];
int size[1000001];
void dfs(int x,int fa){
size[x]=1;
for(int i=head[x];i;i=e[i].next){
int u=e[i].to;
if(u==fa)continue;
dfs(u,x);
size[x]+=size[u];
}
}
void dp(int x,int fa){
for(int i=head[x];i;i=e[i].next){
int u=e[i].to;
if(u==fa)continue;
dp(u,x);
down[x]+=down[u]+size[u];
}
}
void dp2(int x,int fa){
if(fa!=0)
up[x]=up[fa]+down[fa]-down[x]-size[x]+n-size[x];
for(int i=head[x];i;i=e[i].next){
int u=e[i].to;
if(u==fa)continue;
dp2(u,x);
}
}
int main(){
freopen("tree.in","r",stdin);
freopen("tree.out","w",stdout);
n=read();
for(int i=1;i<n;++i){
int x=read(),y=read();
addedge(x,y);addedge(y,x);
}
dfs(1,0);
dp(1,0);
dp2(1,0);
int mx=0;
for(int i=1;i<=n;++i){
if(up[i]+down[i]>up[mx]+down[mx]){
mx=i;
}
}
printf("%d",mx);
return 0;
}