用的换根DP,但是TLE,应该是dfs有问题
#include <bits/stdc++.h>
#define maxx(a,b) a>b?a:b
#define nulls ios::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL);
#define ll long long
using namespace std;
const int N = 1e6+10;
ll head[N*2] , tot = 0;
ll n , m , cnt;
ll g[N] , f[N] , siz[N];
struct node{
ll next , w , to;
}edge[2*N];
void init() {
memset(head , -1 , sizeof head);
tot = 0;
}
void add(ll x ,ll y ) {
edge[tot].to = y;
edge[tot].next = head[x];
head[x] = tot++;
}
void add_ (ll x , ll y) {
add(x , y);
add(y , x);
}
void add(ll x ,ll y , ll z) {
edge[tot].to = y;
edge[tot].next = head[x];
edge[tot].w = z;
head[x] = tot++;
}
void add_ (ll x , ll y , ll z) {
add(x , y , z);
add(y , x , z);
}
void dfs(ll u , ll fa) {
siz[u] = 1;
g[u] = 0;
for(int i = head[u] ; ~i ; i = edge[i].next) {
int v = edge[i].to;
if(v == fa) continue;
dfs(v , u);
siz[u] += siz[v];
g[u] += g[v] + siz[v];
}
}
void sdf(ll u , ll fa) {
for(int i = head[u] ; ~i ; i = edge[i].next) {
int v = edge[i].to;
if(v == fa) continue;
f[v] = f[u] + siz[1] - 2*siz[v];
sdf(v ,u);
}
}
int main() {
nulls
cin >> n;
for(int i = 1 ; i < n ; i++) {
ll x , y;
cin >> x >> y;
add_(x , y);
}
dfs(1 , 0);
f[1] = g[1];
sdf(1 , 0);
ll ans = 0 , x = 0;
for(int i = 1 ; i <= n ; i++) {
if(f[i] > ans) {
ans = f[i];
x = i;
}
}
cout << x;
}