给你一个无根树,问你以哪个节点为根节点的时候得到所有点的深度之和最大
《贴一张 知乎大佬的一个解释》
cpp
#include<bits/stdc++.h>
using namespace std;
const int N = 2e6+10;
using ll = long long;
ll dep[N],sz[N];
ll ans[N];
vector<int>g[N];
int n;
void dfs(int u,int father){
sz[u] = 1;
dep[u] = dep[father]+1;
for(auto &t:g[u]){
if(t==father)continue;
dfs(t,u);
sz[u]+=sz[t];
}
}
void down(int u,int father){
for(auto &t:g[u]){
if(t==father)continue;
ans[t] = ans[u]-2*sz[t]+sz[1];
down(t,u);
}
}
int main()
{
cin>>n;
for(int i=1;i<n;i++){
int a,b;cin>>a>>b;
g[a].push_back(b);
g[b].push_back(a);
}
dfs(1,0);
for(int i=1;i<=n;i++)ans[1]+=dep[i];
//for(int i=1;i<=n;i++)cout<<sz[i]<<"\n";
down(1,-1);
ll res = ans[1],p = 1;
for(int i=1;i<=n;i++)if(ans[i]>res)res=ans[i],p=i;
cout<<p;
}