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;
using ll = long long;
const ll maxn = 2e5+3;
struct edge{
int to,nxt;
}e[maxn<<1];
ll sz[maxn],par[maxn],c[maxn],num[maxn],head[maxn],wch[maxn],tot[maxn],ans[maxn];
ll n;
ll cnt;
ll tmax;
ll sum;
void add_edge(ll u,ll v){
e[++cnt].to = v;
e[cnt].nxt = head[u];
head[u] = cnt;
}
void dfs(ll u,ll p){
sz[u] = 1;
for(ll i=head[u]; i ;i=e[i].nxt){
ll t = e[i].to;
if(t != p){
dfs(t,u);
sz[u] += sz[t];
if(sz[t] > sz[wch[u]]) wch[u] = t;
}
}
}
void cal(ll u,ll p,ll wch,ll val){
tot[c[u]] += val * num[u];
sum += val * num[u];
tmax = max(tmax , tot[c[u]]);
for(ll i=head[u]; i ; i=e[i].nxt){
ll t = e[i].to;
if(t != p and t != wch){
cal(t,u,wch,val);
}
}
}
void dsu(ll u,ll p,ll kp){
for(ll i=head[u]; i ; i=e[i].nxt){
ll t = e[i].to;
if(t != p and t != wch[u]){
dsu(t,u,0);
}
}
if(wch[u]) dsu(wch[u],u,1);
cal(u,p,wch[u],1);
if(2*tmax > sum) ans[u] = sum - tmax;
else ans[u] = sum / 2;
if(!kp) {
cal(u,p,0,-1);
tmax = 0;
sum = 0;
}
}
int main(){
cin>>n;
for(ll i=0;i<n-1;i++){
ll x,y;
cin>>x>>y;
add_edge(x,y); add_edge(y,x);
}
for(ll i=1;i<=n;i++){
ll x,y;
cin>>x>>y;
c[i] = x;
num[i] = y;
}
dfs(1,0);
dsu(1,0,1);
for(int i=1;i<=n;i++){
cout<<ans[i]<<endl;
}
return 0;
}
|