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.
|
|
|
|
#include <bits/stdc++.h>
|
|
|
|
|
using namespace std;
|
|
|
|
|
#define int long long
|
|
|
|
|
#define endl "\n"
|
|
|
|
|
|
|
|
|
|
const int N = 200010, M = N << 1;
|
|
|
|
|
|
|
|
|
|
int 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 sz[N], f[N], g[N], ans;
|
|
|
|
|
|
|
|
|
|
void dfs1(int u, int fa) {
|
|
|
|
|
sz[u] = 1;
|
|
|
|
|
for (int i = h[u]; ~i; i = ne[i]) {
|
|
|
|
|
int v = e[i];
|
|
|
|
|
if (v == fa) continue;
|
|
|
|
|
dfs1(v, u);
|
|
|
|
|
sz[u] += sz[v];
|
|
|
|
|
f[u] += f[v];
|
|
|
|
|
}
|
|
|
|
|
f[u] += sz[u];
|
|
|
|
|
}
|
|
|
|
|
void dfs2(int u, int fa) {
|
|
|
|
|
for (int i = h[u]; ~i; i = ne[i]) {
|
|
|
|
|
int v = e[i];
|
|
|
|
|
if (v == fa) continue;
|
|
|
|
|
g[v] = n - sz[v] + g[u] - sz[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);
|
|
|
|
|
}
|
|
|
|
|
// 第一次dfs,以子孙节点信息更新父节点的统计信息,统计信息包括:以u为根的子树中节点数个sz[u],每个节点可以获取到的权值f[u]
|
|
|
|
|
dfs1(1, 0);
|
|
|
|
|
// f[i]:以1为根时的, 以i为根的子树可以获得的最大权值
|
|
|
|
|
// g[i]:不管以谁为根,以i为根的子树可以获得的最大权值,也就是最终的结果存储数组
|
|
|
|
|
g[1] = f[1]; // g[1]
|
|
|
|
|
|
|
|
|
|
// 第二次dfs,换根
|
|
|
|
|
dfs2(1, 0);
|
|
|
|
|
|
|
|
|
|
// 遍历一遍历,找出到底以谁为根可以获取到权值的最大值,最大值是多少
|
|
|
|
|
int ans = 0;
|
|
|
|
|
for (int i = 1; i <= n; i++) ans = max(ans, g[i]);
|
|
|
|
|
// 输出答案
|
|
|
|
|
cout << ans << endl;
|
|
|
|
|
}
|