You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.1 KiB

#include <bits/stdc++.h>
using namespace std;
const int N = 200010, M = N << 1;
#define int long long
#define endl "\n"
// 链式前向星
int e[M], h[N], idx, w[M], ne[M];
void add(int a, int b, int c = 0) {
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}
int n;
int sz[N];
int f[N];
void dfs(int u, int fa) {
sz[u] = 1;
for (int i = h[u]; ~i; i = ne[i]) {
int v = e[i];
if (v != fa) {
dfs(v, u);
sz[u] += sz[v];
}
}
}
void dp(int u, int fa) {
for (int i = h[u]; ~i; i = ne[i]) {
int v = e[i];
if (v != fa) {
f[v] = f[u] + sz[1] - 2 * sz[v];
dp(v, u);
}
}
}
signed main() {
// 初始化链式前向星
memset(h, -1, sizeof h);
cin >> n;
for (int i = 1; i < n; i++) {
int a, b;
cin >> a >> b;
add(a, b), add(b, a);
}
dfs(1, 0);
for (int i = 1; i <= n; i++) f[1] += sz[i];
dp(1, 0);
int ans = -0x3f;
for (int i = 1; i <= n; i++) ans = max(ans, f[i]);
cout << ans << endl;
}