Here is the most basic operation.
Single-operation time complexity O (logn), Spatial complexity O (N).
1#include <fstream>2#include <iostream>3#include <cstdio>4 5 using namespacestd;6 7 intn,m;8 inta[100002],tree[100002];9 Ten voidBuild ();//Array of achievements One intReadintPOS);//the answer to Sum[1,pos] A voidUpdateintPosintVal);//Add A[pos] to v - - intMain () the { - //freopen ("d:\\input.in", "R", stdin); - //freopen ("D:\\output.out", "w", stdout); - intbo,t1,t2; +scanf"%d%d",&n,&m); - for(intI=1; i<=n;i++) +scanf"%d",&a[i]); A build (); at for(intI=1; i<=m;i++) - { -scanf"%d%d%d",&bo,&t1,&T2); - if(bo) - Update (T1,T2); - Else inprintf"%d\n", read (T2)-read (t1-1)); - } to return 0; + } - voidbuild () the { *tree[0]=0; $ for(intI=1; i<=n;i++)Panax Notoginseng { -tree[i]=A[i]; the for(intj=i-1; j>i-(i& (-i)); j=j-(j& (-J ))) + { Atree[i]+=Tree[j]; the } + } - } $ intReadintPOS) $ { - intans=0; - while(pos>0) the { -ans+=Tree[pos];Wuyipos-=pos& (-POS); the } - returnans; Wu } - voidUpdateintPosintval) About { $ while(pos<=N) - { -tree[pos]+=Val; -pos+=pos& (-POS); A } +}View Code
Tree array single point update and interval query