Rujia: "Training Guide" Page (194)
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <algorithm>using namespace std;//One-dimensional tree-shaped array base template int lowbit (int x) {return x& (-X);} int c[1001];int sum (int x)//calculates the array elements from 1 to x and {int s=0; while (x>0) {s=s+c[x]; X=x-lowbit (x); } return s;} void Add (int x, int D)//will increase the value of a (x) by D, or you can subtract a value {while (x<=1000)///1000 Here is the cap of the array I opened, which is a change based on the data of the topic {c[x]=c[ X]+d; X=x+lowbit (x); }}int Main () {int a[1001]; int I, J; for (i=0; i<=1000; i++) {a[i]=i; } c[0]=0; for (I=1; i<=1000; i++)//have a[] array to calculate c[] array value {c[i]=0; For (J=i-lowbit (i) +1; j<=i; J + +) {C[i]=c[i]+a[j]; }//} int x; scanf ("%d", &x); printf ("%d\n", sum (x)); Query the 1->x of a[] and int y; scanf ("%d", &y); Add (x, y); A[] The element labeled X is increased by D printf ("%d\n", sum (x)); return 0;}
Tree Array (binary index tree BIT Fenwick Tree) * "One-dimensional base template" (query interval and + modify update)