Data Structures & AlgorithmsVery hardCodeforces Div2 D · ICPC regional
A bottom-up segment tree for the sum over n = 8 cells stores leaf i at t[n + i] and builds t[i] = t[2i] op t[2i + 1] for i = n − 1 down to 1. The initial array is a = [6, 7, 2, 2, 5, -3, -2, 8]. Then the operations run in order: set(2, -2), set(6, 6), set(2, 1), set(0, 0), where set(p, v) puts v at t[n + p] and then recomputes every ancestor on the path to the root. Finally query(l, r) runs over the half-open range [l, r) with the usual loop (l += n; r += n; while l < r: if l is odd take t[l] and l += 1; if r is odd take t[r − 1] and r −= 1; l /= 2; r /= 2). With l = 2 and r = 7, what does query return?
- A. 19
- B. 12
- C. 11
- D. 5
Correct answer: C. 11
The leaves hold the updated values, but an ancestor is only correct if every set walked up the tree. The query covers the cells l through r − 1; using r or r − 1 as the end, or ignoring the updates to internal nodes, gives a different value.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- A bottom-up segment tree for the sum over n = 9 cells stores leaf i at t[n + i] and builds t[i] = t[2i] op t[2i + 1] for i = n − 1 down to…
- A bottom-up segment tree for the sum over n = 8 cells stores leaf i at t[n + i] and builds t[i] = t[2i] op t[2i + 1] for i = n − 1 down to…
- A bottom-up segment tree for the sum over n = 5 cells stores leaf i at t[n + i] and builds t[i] = t[2i] op t[2i + 1] for i = n − 1 down to…
- A bottom-up segment tree for the sum over n = 9 cells stores leaf i at t[n + i] and builds t[i] = t[2i] op t[2i + 1] for i = n − 1 down to…
- A bottom-up segment tree for the sum over n = 5 cells stores leaf i at t[n + i] and builds t[i] = t[2i] op t[2i + 1] for i = n − 1 down to…
- A bottom-up segment tree for the sum over n = 7 cells stores leaf i at t[n + i] and builds t[i] = t[2i] op t[2i + 1] for i = n − 1 down to…