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));
}- A. 5 11
- B. 5 9
- C. 7 11
- 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
- Assume int is 32 bits. What is printed? c #include <stdint.h> #include <stdio.h> int main(void) { uint8t b = 0xF3; int e = (int)(b ^…
- What is printed? c #include <stdint.h> #include <stdio.h> int tz(uint32t x) { int n = 0; while (!(x & 1u)) { x >>= 1; n++; } return n; }…
- Assume int is 32 bits with limits INTMIN = -2147483648 and INTMAX = 2147483647. What is printed? c #include <limits.h> #include <stdio.h>…
- int n = 8, c = 0; for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j = 2) c++; printf("%d", c); What is printed?
- int c = 0; for (int i = 1; i <= 100; i = 3) c++; printf("%d", c); What is printed?
- int c = 0; for (int i = 100; i >= 1; i /= 2) c++; printf("%d", c); What is printed?