Data Structures & AlgorithmsVery hardCodeforces Div2 C · ICPC regional

A Fenwick tree on 1..10 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(7, -4), add(3, 5), add(1, 3), add(5, -1), add(3, 1), add(3, 1), add(9, 4), add(2, 3). Then query(3) is run as s = 0; j = 3; while j > 0: s += t[j]; j −= j & −j; and returns s. What does query(3) return?

  1. A. 6
  2. B. 12
  3. C. 13
  4. D. 16

Correct answer: C. 13

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.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic