Segment tree study notes (primary: Only plus range, interval sum)

We studied the tree line theory for a long time and found that it played again and consequently understand the code

In simple terms, the segment tree is the partition of the interval to make edits based, it is high time efficiency

Then it is the code (Luo Gu too pit, query inside ans also open long long)

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 #include <algorithm>
 5 using namespace std;
 6 typedef long long ll;
 7 const int N = 1e5 + 5;
 8 ll addv[N*4],sumv[N*4],a[N];
 9 int n,m;
10 inline int read()
11 {
12     int x=0,w=1; char c=getchar();
13     while (c>'9'|| c<'0') {if(c=='-') w=-1; c=getchar();}
14     while (c<='9'&&c>='0') {x=(x<<1)+(x<<3)+c-'0'; c=getchar(); }
15     return w*x;
16 }
17 void pushup(int k)
18 {
19     sumv[k]=sumv[k<<1]+sumv[k<<1|1];
20 }
21 inline void build(int o,int l,int r)//建树
22 {
23     if (l==r) {sumv[o]=a[l]; return ;}
24     int mid=(l+r)>>1;//分治操作
25     build(o<<1,l,mid);
26     build(o<<1|1,mid+1,r);
27     a pushup (O);
 28  }
 29  void pushdown ( int O, int L, int R & lt) // metaphysical pushdown (derived from the operation from the tree)
 30  {
 31 is      IF (ADDV [O] == 0 ) return ;
 32      ADDV [O << . 1 ] + = ADDV [O];
 33 is      ADDV [O << . 1 | . 1 ] + = ADDV [O];
 34 is      int MID = (L + R & lt) >> . 1 ;
 35      sumv [O << . 1 ] + = ADDV [O] * (L +-MID . 1 );
 36      sumv [O << . 1| . 1 ] + = ADDV [O] * (R- MID);
 37 [      ADDV [O] = 0 ;
 38 is  }
 39  void puttag ( int O, int L, int R & lt, V LL) // lazytag operation, lazy marker
 40  {
 41 is      ADDV [O] + = V;
 42 is      sumv [O] + = (R & lt-L + . 1 ) * V;
 43 is  }
 44 is  void Modify ( int O, int L, int R & lt, int QL, int QR, LL V) // modify section
 45  {
 46 is      IF(QL <= L && QR> = R & lt) {puttag (O, L, R & lt, V); return ;}
 47      int ANS = 0 , MID = (L + R & lt) >> . 1 ;
 48      pushdown (O, L, R & lt) ; // pushdown not forget where
 49      IF (QL <= MID) Modify (O << . 1 , L, MID, QL, QR, V);
 50      IF (QR> MID) Modify (O << . 1 | . 1 , + MID . 1 , R & lt, QL, QR, V);
 51 is      a pushup (O);    
 52 is  }
 53 is LL query ( int O, int L, int R & lt, int QL, int QR) // query section
 54  {
55     if (ql<=l&&qr>=r) return sumv[o];
56     pushdown(o,l,r);
57     ll ans=0;
58     int mid=(l+r)>>1;
59     if (ql<=mid) ans+=query(o<<1,l,mid,ql,qr);
60     if (qr>mid) ans+=query(o<<1|1,mid+1,r,ql,qr);
61     return ans;
62 }
63 int main()
64 {
65     n=read(); m=read();    
66     for(int i=1;i<=n;++i)
67         scanf("%lld",&a[i]);
68     build(1,1,n);
69     while(m--)
70     {
71         int opt,l,r;
72         ll val;
73         opt=read();
74         if (opt==1) l=read(),r=read(),scanf("%lld",&val),modify(1,1,n,l,r,val);
75         else l=read(),r=read(),printf("%lld\n",query(1,1,n,l,r));
76     }
77     return 0;
78 }

To be continued...

Guess you like

Origin www.cnblogs.com/cptbtptpbcptbtptp/p/11605615.html