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 = [1, -5, 6, -1, -4, -5, 9, -4]. Then the operations run in order: set(4, 9), set(1, 6), set(1, -3), set(0, -5), 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 = 3 and r = 5, what does query return?
- A. -1
- B. 8
- C. -5
- D. 3
Correct answer: B. 8
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 maximum 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…
- Start with an empty binary min-heap stored in an array, where the children of index i are at 2i + 1 and 2i + 2. insert(x) appends x and…
- Start with an empty binary min-heap stored in an array, where the children of index i are at 2i + 1 and 2i + 2. insert(x) appends x and…
- Directed graph on vertices 0 to 7 with weighted edges (u→v (w)): 7→5 (4), 3→6 (8), 7→3 (9), 5→4 (3), 7→2 (10), 3→2 (2), 1→4 (12), 4→3 (3)…
- Directed graph on vertices 0 to 8 with weighted edges (u→v (w)): 8→7 (11), 0→1 (7), 5→8 (4), 5→1 (1), 4→1 (10), 8→5 (11), 7→8 (11), 3→5…
- Directed graph on vertices 0 to 5 with weighted edges (u→v (w)): 1→0 (8), 1→2 (1), 3→5 (5), 2→5 (6), 3→1 (1), 3→4 (9), 5→4 (7), 4→0 (11)…