How to upgrade a normal tree-like array
Ordinary single-point modified single-point query will not talk about, from the interval modification and single-point query.
The original value exists a[] inside, multi-set c1[], note: c1[i]=a[i]-a[i-1].
A[i]=a[i-1]+c1[i]=a[i-2]+c1[i]+c1[i-1]=.....=c1[1]+c1[2]+...+c1[i] When you ask for the value of A[i].
So just use c1[] to create a tree-like array, you can quickly query the value of A[i]. Not much to say, see Code.
#include <iostream>#include<cstdio>#defineLB (x) x&-x#defineMAXN 1000000#defineIn (x) scanf ("%d", &x)#definein3 (x, Y, z) scanf ("%d%d%d", &x,&y,&z)using namespacestd;inta[maxn],c1[maxn],n,m,val,x,y,temp;voidUpdateintXintval) { while(x<=N) {c1[x]+=Val; X+=lb (x); }}intSumintx) { intans=0; while(x) {ans+=C1[x]; X-=lb (x); } returnans;} Main () {inch(n); inch(m); for(intI=1; i<=n;i++) { inch(A[i]); Update (I,A[I)-a[i-1]); } while(m--) { inch(temp); if(temp==1) { inch(x); printf ("%d\n", sum (x)); } Else{in3 (x,y,val); Update (X,VAL); Update (Y+1,-val); } }}
Self-thought or relatively good-looking understand, followed by interval modification and interval query.
We use SUM (1,k) to denote intervals of 1 to K.
Then sum (1,k) =C1 (1) + (C1 (2) +C1 (2)) + (C1 (1) +C1 (2) +C1 (3)) +...+ (C1 (1) +C1 (2) +...+c1 (k)).
Then we bashi the child open.
SUM (1,k) =k* (C1 (1) +C1 (2) +c1 (3) +...+c1 (k))-(0*c1* (1) +1*c1 (2) +2*c1 (3) +...+ (k-1) *c1 (k)).
is not a little excited, we can build an array c2[],c2[n] to save (n-1) *C1 (n), and the C2 array is also established as a tree array, then the problem is solved.
See the code:
#include <iostream>#include<cstdio>#defineLB (x) x&-x#defineMAXN 1000000#defineIn (x) scanf ("%d", &x)#definein3 (x, Y, z) scanf ("%d%d%d", &x,&y,&z)using namespacestd;inta[maxn],c1[maxn],c2[maxn],n,m,val,x,y,temp;voidUpdateint*q,intXintval) { while(x<=N) {q[x]+=Val; X+=lb (x); }}intGetsum (int*q,intx) { intans=0; while(x) {ans+=Q[x]; X-=lb (x); } returnans;}intSumintx) { intAns1,ans2; Ans1=x*getsum (c1,x); Ans2=getsum (c2,x); returnAns1-ans2;}intInquireintXinty) { intAns1,ans2; Ans1=sum (y); Ans2=sum (x1); returnAns1-Ans2;} Main () {inch(n); inch(m); for(intI=1; i<=n;i++) { inch(A[i]); Update (C1,I,A[I)-a[i-1]); Update (C2,i, (i-1) * (a[i]-a[i-1])); } for(intI=1; i<=m;i++) { inch(temp); if(temp==1) {in3 (x,y,val); Update (C1,X,VAL); Update (C1,y+1,-val); Update (C2,x, (x-1)*val); Update (C2,y+1,-y*val); } Else { inch(x); inch(y); printf ("%d\n", Inquire (x, y)); } }}
Interval modification and single-point query and interval query of tree array