-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsumOfDistanceOfAllNodes.cpp
More file actions
90 lines (79 loc) · 1.55 KB
/
sumOfDistanceOfAllNodes.cpp
File metadata and controls
90 lines (79 loc) · 1.55 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
76
77
78
79
80
81
82
83
84
85
86
87
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
const long long INF = 1e18;
const int32_t M = 1e9 + 7;
const int32_t MM = 998244353;
ll sum[200001];
vector<ll> adj[200001];
ll ans[200001];
ll subnodes[200001];
ll n;
void calc_sum(ll src,ll par)
{
ll maxH=0;
bool leaf=true;
ll cnt=1;
for(auto x:adj[src])
{
if(x!=par)
{
leaf=false;
calc_sum(x,src);
cnt+=subnodes[x];
maxH+=sum[x]+subnodes[x];
}
}
if(leaf)
{ subnodes[src]=1;
sum[src]=0;
return;
}
subnodes[src]=cnt;
sum[src]=maxH;
return;
}
void calc_maxDist(ll src,ll par,ll partial_ans)
{
ans[src]=sum[src]+partial_ans+(n-subnodes[src]);
for(auto x:adj[src])
{
if(x!=par)
{
calc_maxDist(x,src,ans[src]-sum[x]-subnodes[x]);
}
}
return;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("otpt.txt", "w", stdout);
#endif
ll t = 1;
// cin >> t;
while (t--)
{
memset(adj,0,sizeof adj);
memset(ans,0,sizeof ans);
memset(sum,0,sizeof sum);
memset(subnodes,0,sizeof subnodes);
n=0;
cin>>n;
for(ll i=0;i<n-1;i++)
{
ll a,b;
cin>>a>>b;
adj[a].push_back(b);
adj[b].push_back(a);
}
calc_sum(1,0);
calc_maxDist(1,0,0);
for(ll i=1;i<=n;i++)
{
cout<<ans[i]<<" ";
}
cout<<endl;
}
return 0;
}