ProgrammingVery hardCompetitive coding (CP)

What is printed?

What is printed?
#include <stdio.h>
int bit[9] = {0};
void add(int i, int v) {
    for (; i <= 8; i += i & -i) bit[i] += v;
}
int query(int i) {
    int s = 0;
    for (; i > 0; i -= i & -i) s += bit[i];
    return s;
}
int main(void) {
    add(3, 5);
    add(5, 2);
    add(6, 4);
    printf("%d %d", query(4), query(6));
}
  1. A. 5 11
  2. B. 5 9
  3. C. 7 11
  4. D. 5 6

Correct answer: A. 5 11

A Fenwick tree stores partial sums: query(4) reads bit[4] = 5, and query(6) reads bit[6] + bit[4] = 6 + 5 = 11. The update step i += i & -i moves to the parent node.

More C Programming questions

Exams that ask this topic