题目
题意: 给定一个 n 个点的树,请求出一个结点,使得以这个结点为根时,所有结点的深度之和最大。
一个结点的深度之定义为该节点到根的简单路径上边的数量。
思路: 换根dp.
1.先以任意一个点为根dfs1,求出f[root]。
2.考虑换根。看由u换成其子节点j之后的影响,进行dfs2。
从而在O(n)的时间内完成换根,得到。
f[j] = f[u] - s[j] + n - s[j]
时间复杂度: O(n)
代码:
// Problem: P3478 [POI2008] STA-Station
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P3478
// Memory Limit: 256 MB
// Time Limit: 2000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<complex>
#include<cstring>
#include<cmath>
#include<vector>
#include<map>
#include<unordered_map>
#include<list>
#include<set>
#include<queue>
#include<stack>
#define OldTomato ios::sync_with_stdio(false),cin.tie(nullptr),cout.tie(nullptr)
#define fir(i,a,b) for(int i=a;i<=b;++i)
#define mem(a,x) memset(a,x,sizeof(a))
#define p_ priority_queue
// round() 四舍五入 ceil() 向上取整 floor() 向下取整
// lower_bound(a.begin(),a.end(),tmp,greater<ll>()) 第一个小于等于的
// #define int long long //QAQ
using namespace std;
typedef complex<double> CP;
typedef pair<int,int> PII;
typedef long long ll;
// typedef __int128 it;
const double pi = acos(-1.0);
const int INF = 0x3f3f3f3f;
const ll inf = 1e18;
const int N = 1e6+10;
const int M = N<<1;
const int mod = 1e9+7;
const double eps = 1e-6;
inline int lowbit(int x){ return x&(-x);}
template<typename T>void write(T x)
{
if(x<0)
{
putchar('-');
x=-x;
}
if(x>9)
{
write(x/10);
}
putchar(x%10+'0');
}
template<typename T> void read(T &x)
{
x = 0;char ch = getchar();ll f = 1;
while(!isdigit(ch)){if(ch == '-')f*=-1;ch=getchar();}
while(isdigit(ch)){x = x*10+ch-48;ch=getchar();}x*=f;
}
int n,m,k,T;
int h[N],e[M],ne[M],idx = 0;
void add(int a,int b)
{
e[idx] = b,ne[idx] = h[a],h[a] = idx++;
}
int d[N]; //深度
ll f[N]; //以u为根的最大价值
int s[N]; //以u为根的子树大小
void dfs1(int u,int fa)
{
s[u] = 1;
for(int i=h[u];~i;i=ne[i])
{
int j = e[i];
if(j==fa) continue;
d[j] = d[u]+1;
dfs1(j,u);
s[u] += s[j];
}
}
void dfs2(int u,int fa)
{
for(int i=h[u];~i;i=ne[i])
{
int j = e[i];
if(j==fa) continue;
f[j] = f[u] + n - 2*s[j];
dfs2(j,u);
}
}
void solve()
{
read(n); mem(h,-1);
for(int i=0;i<n-1;++i)
{
int x,y; read(x),read(y);
add(x,y),add(y,x);
}
dfs1(1,0);
for(int i=2;i<=n;++i) f[1] += d[i];
dfs2(1,0);
int idx = 1;
for(int i=2;i<=n;++i) if(f[i] > f[idx]) idx = i;
write(idx);
}
signed main(void)
{
T = 1;
// OldTomato; cin>>T;
// read(T);
while(T--)
{
solve();
}
return 0;
}