Pondo Subtree Add
View as PDFYou are given a tree with vertices, rooted at vertex
. Each vertex
has an integer
value
. You must process
queries of two types:
1 v x: addto the value of every vertex in the subtree of
(including
itself)
2 u: output the current value of vertex
Use the enter/exit Euler tour from Pondo Euler Tour. The subtree of occupies the
contiguous range
on that tour, so a subtree add is a
range add and a vertex query is a point query at
.
The Fenwick tree below supports range add and point query. range_add(l, r, x) adds to
every index in
(inclusive, 0-indexed).
point(i) returns the value at index .
class Fenwick:
def __init__(self, n):
self.n = n
self.bit = [0] * (n + 1)
def add(self, i, delta):
while i <= self.n:
self.bit[i] += delta
i += i & -i
def prefix(self, i):
s = 0
while i > 0:
s += self.bit[i]
i -= i & -i
return s
def range_add(self, left, right, delta):
self.add(left + 1, delta)
self.add(right + 2, -delta)
def point(self, i):
return self.prefix(i + 1)
Input
The first line contains two integers and
.
The second line contains integers
, the initial values of the
vertices.
Each of the next lines contains two integers
and
, denoting an undirected
edge between
and
.
Each of the next lines describes a query and is one of the following:
1 v x: addto every vertex in the subtree of
2 u: query the value of vertex
Vertices are numbered through
. The edges form a tree.
Output
For each query of type 2, print a line containing the current value of that vertex.
Constraints
Example 1
Input
8 9
0 0 0 0 0 0 0 0
1 2
2 3
2 4
1 5
5 6
6 7
6 8
1 2 10
2 3
2 5
1 1 5
2 3
2 7
1 6 -3
2 7
2 1
Output
10
0
15
5
2
5
Explanation
The tree, rooted at , looks like this:
1
/ \
2 5
/ \ \
3 4 6
/ \
7 8
- Adding
to the subtree of
changes vertices
.
- Vertex
is then
, and vertex
is still
.
- Adding
to the subtree of
changes every vertex.
- Vertex
becomes
and vertex
becomes
.
- Adding
to the subtree of
changes vertices
, so vertex
becomes
.
- Vertex
is
.
Example 2
Input
5 7
1 2 3 4 5
1 2
1 3
3 4
3 5
2 1
1 3 10
2 4
2 2
1 1 -1
2 5
2 1
Output
1
14
2
14
0
Comments