Data Structures & AlgorithmsVery hardCodeforces Div2 C · ICPC regional
A Fenwick tree on 1..9 starts all zero and receives add(i, v) implemented as j = i; while j ≤ n: t[j] += v; j += j & −j. The calls, in order, are add(1, -1), add(1, 2), add(3, -4), add(9, 1), add(6, 5), add(7, 1), add(4, 1). Then query(7) is run as s = 0; j = 7; while j > 0: s += t[j]; j −= j & −j; and returns s. What does query(7) return?
- A. 2
- B. 3
- C. 4
- D. 5
Correct answer: C. 4
The query visits the nodes k, k minus its lowest set bit, and so on, so it sums exactly the prefix a[1..k]. Adding up the tree entries directly, or querying k − 1, gives a different total.
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 = 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…
- 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…
- A bottom-up segment tree for the sum over n = 6 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 maximum over n = 6 cells stores leaf i at t[n + i] and builds t[i] = t[2i] op t[2i + 1] for i = n − 1…
- 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…