#include <iostream>#include "Cstdio"#include "string.h"using namespace Std;Const intn=100005;structnode{intLeftintRightintAddintsum;} tree[n*4];intN,m;intA[n];voidInit () {memset (tree,0,sizeof(tree)); Memset (A,0,sizeof(a));}//Return the following updated values to the previous layervoidPushup (int ID) {tree[ID]. Sum=tree[ID*2]. Sum+tree[ID*2+1]. Sum;}//Move the marker range downvoidPushdown (int ID) {tree[ID*2]. Add=tree[ID*2]. Add+tree[ID]. Add; tree[ID*2]. Sum=tree[ID*2]. Sum+ (tree[ID*2]. Right-tree[ID*2]. Left+1) *tree[ID]. Add; tree[ID*2+1]. Add=tree[ID*2+1]. Add+tree[ID]. Add; tree[ID*2+1]. Sum=tree[ID*2+1]. Sum+ (tree[ID*2+1]. Right-tree[ID*2+1]. Left+1) *tree[ID]. Add; tree[ID]. Add=0;}//Make a contribution to the upper level each time you build the next layervoidBuildint ID,intLintR) {tree[ID]. Left=l; tree[ID]. Right=r; tree[ID]. Add=0; tree[ID]. Sum=0;if(L==R) {tree[ID]. Sum=A[L];return; }intMid= (L+R)/2; BuildID*2, L,mid); BuildID*2+1, mid+1, R); Pushup (ID);}voidAddint ID,intLintRintVal) {//If the current interval is fully contained, only the sum of the current interval is updated //and add marker to the interval if(tree[ID]. Left>=l&&tree[ID]. Right<=R) {tree[ID]. Add=tree[ID]. Add+val; tree[ID]. Sum=tree[ID]. Sum+ (tree[ID]. Right-tree[ID]. Left+1) *val;return; }//If the current interval is not included if(tree[ID]. Right<l| | tree[ID]. Left>R)return;//If the current interval portion is included, the marker moves down if(tree[ID]. Add) Pushdown (ID);//Update left and right sub-zonesAddID*2, L,r,val); AddID*2+1, L,r,val);//Update and return the results to the topPushup (ID);}intAnsvoidQueryint ID,intLintR) {//query interval outside this interval if(tree[ID]. Left>r| | tree[ID]. Right<L)return;//The interval is fully contained if(tree[ID]. Left>=l&&tree[ID]. Right<=R) {ans=ans+tree[ID]. Sum;return; }//Query part of this interval, mark down move if(tree[ID]. Add) Pushdown (ID);//Around search intMid= (tree[ID]. Left+tree[ID]. Right)/2;if(l<=mid) Query (ID*2, l,r);if(r>mid) Query (ID*2+1, l,r);}intMain () {//freopen ("In.txt", "R", stdin); while(SCANF ("%d%d", &n,&m)!=eof) {init ();Chars[Ten]; for(intI=1; i<=n; i++) scanf ("%d", &a[i]); Build1,1, n); for(intI=1; i<=m; i++) {intA,b,c; scanf'%s ', s);if(s[0]==' Q ') {ans=0; scanf"%d%d", &a,&b); Query1, A, b); printf"%d\n", ans); }if(s[0]==' C ') {scanf (" %d%d%d", &a,&b,&c); Add1, a,b,c); } } }//fclose (stdin); return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Segment Tree Interval Update template