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.

63 lines
1.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#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 f[N];
int g[N];
// 第一次dfs,向下向上,生成汇总信息
void dfs1(int u, int fa) {
f[u] = 1; // 以u为根的子树大小初始时有u一个节点sz[u]=1
for (int i = h[u]; ~i; i = ne[i]) {
int v = e[i];
if (v != fa) {
// 先填充子孙节点的统计信息
dfs1(v, u);
// 利用子孙节点的统计信息汇总生成u节点的连通块节点个数统计信息
f[u] += f[v];
}
}
}
// 第二次dfs,向上向下
void dfs2(int u, int fa) {
for (int i = h[u]; ~i; i = ne[i]) {
int v = e[i];
if (v != fa) {
g[v] = g[u] + f[1] - 2 * f[v];
dfs2(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);
}
dfs1(1, 0);
for (int i = 1; i <= n; i++) g[1] += f[i];
dfs2(1, 0);
int ans = 0;
for (int i = 1; i <= n; i++) ans = max(ans, g[i]);
cout << ans << endl;
}