-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreRootingTree.cpp
More file actions
75 lines (63 loc) · 1.29 KB
/
Copy pathreRootingTree.cpp
File metadata and controls
75 lines (63 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//http://codeforces.com/contest/1187/problem/E
#include<iostream>
#include<vector>
#define N 2*100001
using namespace std;
vector<int> adjList[N];
long long subtreeSize[N];
long long dp[N];
long long ans;
void calSize(int node,int parent){
subtreeSize[node]=1;
for(auto child: adjList[node]){
if(child!=parent){
calSize(child,node);
subtreeSize[node]+=subtreeSize[child];
}
}
}
void calDp(int node,int parent){
dp[node]=subtreeSize[node];
for(auto child: adjList[node]){
if(child!=parent){
calDp(child,node);
dp[node]+=dp[child];
}
}
}
void dfs(int node,int parent){
ans=max(ans,dp[node]);
for(auto child: adjList[node]){
if(child!=parent){
dp[node]-=dp[child];
dp[node]-=subtreeSize[child];
subtreeSize[node]-=subtreeSize[child];
dp[child]+=dp[node];
dp[child]+=subtreeSize[node];
subtreeSize[child]+=subtreeSize[node];
dfs(child,node);
subtreeSize[child]-=subtreeSize[node];
dp[child]-=subtreeSize[node];
dp[child]-=dp[node];
subtreeSize[node]+=subtreeSize[child];
dp[node]+=dp[child];
dp[node]+=subtreeSize[child];
}
}
}
int main(){
int n;
cin>>n;
for(int i=0;i<n-1;i++){
int x,y;
cin>>x>>y;
adjList[x].push_back(y);
adjList[y].push_back(x);
}
ans=0;
calSize(1,0);
calDp(1,0);
dfs(1,0);
cout<<ans<<endl;
return 0;
}