https://www.luogu.org/problemnew/show/P3374
1#include <iostream>2#include <cstdio>3 using namespacestd;4 #defineRson (o<<1|1)5 #defineLson (o<<1)6 Const intN =530000<<1;//zkw Line tree can only query (0,bit), so only bit-2 leaf nodes, bit-2<n to expand7 intm, N, Tree[n], M, q;8InlineintRead () {9Registerintc = GetChar (), x =0, F =1; Ten while(!isdigit (c)) {if(c = ='-') F =-1; c =GetChar ();} One while(IsDigit (c)) x = (x<<3) + (x<<1) + (c^ -), C =GetChar (); A returnx*F; - } -InlinevoidPushup (into) { theTree[o] = Tree[lson] +Tree[rson]; - } -Inlinevoidbuild () { - for(M =1; M < n; M <<=1); + for(inti =1; I <= N; ++i) Tree[i+m] =read (); - for(inti = m1; I --i) pushup (i); + } AInlinevoidUpdateintPosintk) { at for(Tree[pos+=m]+=k, pos>>=1;p os;pos>>=1) - pushup (POS); - } -InlineintSum (intLintR) { - intAns =0; - //l=l+m-1-> change between Sany to l-1,r=r+m+1-> change Sany between R+1 in //l^r^1, equivalent to judging if L and R are sibling nodes - for(l=l+m-1, r=r+m+1; l^r^1; l>>=1, r>>=1){ to if(~l&1)//l%2==0-->l left son +Ans + = tree[l^1]; - if(r&1)//r%2==1 theAns + = tree[r^1]; * } $ returnans;Panax Notoginseng } - intMainvoid){ then = Read (), M =read (); + build (); A while(m--){ the intopt = read (), x = Read (), y =read (); + if(opt==1) update (x, y); - Elseprintf"%d\n", Sum (x, y)); $ } $ return 0; -}
zkw Segment Tree
1#include <bits/stdc++.h>2 using namespacestd;3 4 #defineLowbit (a) a& (a)5 6 Const intN =500010;7 8 intA[n], N, M, X, Y, K;9 TenInlinevoidUpdateintXintk) { One while(x <=N) { AA[X] + =K; -X + =lowbit (x); - } the } - -InlineintSum (intx) { - intAns =0; + while(X >0){ -Ans + =A[x]; +X-=lowbit (x); A } at returnans; - } - - intMainvoid){ -scanf"%d%d", &n, &m); - for(inti =1; I <= N; ++i) { in inttmp scanf"%d", &tmp); update (i,tmp); - } to while(m--){ + intBS; -scanf"%d%d%d", &bs, &x, &y); the if(bs = =1) update (x, y); * Elseprintf"%d\n", Sum (y)-sum (X-1)); $ }Panax Notoginseng - return 0; the}
tree-like array
[Template] tree-like array 1/zkw segment tree