Question: Can we use linear data structure to solve the problem of dynamic statistics subtree right ? Yes, a tree-like array.
Assuming the current array is a[], the number of elements is n.
1. The weights and arrays of the sub-interval are sum, then the array elements of the interval between I and J in the array a[] and the summation of sum[i,j]= a[k] "K Belongs to (I->J)"
2. Now define the prefix and array s[],s[i] to represent the sum from a[i]---a[i], then this can be represented sum[i,j] = s[j]-s[i-1].
3. Lowbit (k) is the number represented by the first 1 on the right of the binary representation of the integer k, lowbit (k) =k& (-K).
4. The tree array for c[],c[k] stores the sum of the lowbit (k) elements from the a[k] beginning to the lower subscript, and the first layer of traversal.
Note: We want to store the elements of the a[] array starting with subscript 1.
Here's a list:
C[1]=A[1]; S[1]=C[1];
C[2]=A[2]+A[1]; S[2]=C[2];
C[3]=A[3]; S[3]=C[3]+C[2];
C[4]=A[4]+A[3]+A[2]+A[1]; S[4]=C[4];
C[5]=A[5]; S[5]=C[5]+C[4];
C[6]=A[6]+A[5]; S[6]=C[6]+C[4];
C[7]=A[7]; S[7]=C[7]+C[6]+C[4];
C[8]=A[8]+A[7]+A[6]+A[5]a[4]+a[3]+a[2]+a[1]; S[8]=C[8];
C[9]=A[9]; S[9]=C[9]+C[8];
5. The complexity of calculating each s[i] is O (log2 (n)).
6. Code:
#include <stdio.h> #include <string.h>int a[101];int c[101];int s[101];int lowbit (int x) { return x& (-X);} int sum (int x) { int s=0; while (x>0) { s+=c[x]; X=x-lowbit (x); } return s;} int main () { int i, j, K; for (I=1; i<=10; i++) a[i]=i;//create a[] array for (i=1; i<=10; i++) {//calculate each c[i] C[i]=0;//c[i] from initial 0 For (J=i-lowbit (i) +1; j<=i; J + +) { c[i]+=a[i];} } for (I=1; i<=10; i++) { s[i]=sum (i);//calculate the prefix array for I and } return 0;}
"Tree-like array"