-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSubtree Queries.cpp
88 lines (73 loc) · 2 KB
/
Subtree Queries.cpp
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
88
#include "bits/stdc++.h"
using namespace std;
#define pii pair<int,int>
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define ll long long
//<<<<<<<<<<Segment Tree>>>>>>>>>>>>>>>\\
const int N = 2e5+5;
const int D = 19;
const int S = (1<<D);
int n, q, v[N];
vector<int> adj[N];
int sz[N], p[N], dep[N];
ll st[S], euler[N], tp[N];
void update(int idx, int val) {
st[idx += n] = val;
for (idx /= 2; idx; idx /= 2)
st[idx] = st[2 * idx]+ st[2 * idx + 1];
}
ll query(int lo, int hi) {
ll ra = 0, rb = 0; //<< Don't forget to pre initialize the starting value
for (lo += n, hi += n + 1; lo < hi; lo /= 2, hi /= 2) {
if (lo & 1)
ra = ra+ st[lo++];
if (hi & 1)
rb = rb+ st[--hi];
}
return ra+rb;
}
//<<<<<<<<<<Segment Tree Ends>>>>>>>>>>>>>>>\\
int ct = 1;
int dfs(int cur, int par) {
euler[cur] = ct++;
sz[cur] = 1;
p[cur] = par;
update(euler[cur], v[cur]); //< We assign the values against the euler id, so we can create segment trees on that
for(int chi : adj[cur]) {
if(chi == par) continue;
dep[chi] = dep[cur] + 1;
p[chi] = cur;
sz[cur] += dfs(chi, cur);
}
return sz[cur];
}
int main() {
scanf("%d%d",&n,&q);
for(int i=1; i<=n; i++) scanf("%d", &v[i]); //< Property on nodes
for(int i=2; i<=n; i++) {
int a, b;
scanf("%d%d", &a, &b);
adj[a].push_back(b);
adj[b].push_back(a);
}
dfs(1,-1);
while(q--) {
int t;
cin>>t;
if(t == 1) {
int s, x;
scanf("%d%d", &s, &x);
v[s] = x;
update(euler[s],x); //< We update the property against the euler id
} else {
int a;
scanf("%d", &a);
ll res = query(euler[a],euler[a] + sz[a] - 1); //< Here we search between the euler id
//and euler id + substree size, cuase thats how euler tour works
printf("%lld\n", res);
}
}
}