2019.9.8 segment tree template

. 1  // luogu judger-enable-O2- 
2 #include <cstdio>
 . 3  the using  namespace STD;
 . 4  const  int N = 1E5 + . 5 ;
 . 5  Long  Long Tree [ . 4 * N], A [N], m, n-, X, Y, Z, D, the lazy [ 4 * N]; // open into the data array is generally four times the range of N
 . 6  void pushdown ( int P, int L, int R & lt) tag downstream // the lazy
 . 7  {
 . 8      int MID = (L + R & lt) >> . 1 ;
 . 9      Tree [P * 2 ] + = (L +-MID . 1 ) *the lazy [P];
 10      the lazy [P * 2 ] + = the lazy [P];
 . 11      Tree [P * 2 + . 1 ] + = (R & lt-MID) * the lazy [P];
 12 is      the lazy [P * 2 + . 1 ] = + the lazy [P];
 13 is      the lazy [P] = 0 ;
 14  }
 15  void BuildTree ( int P, / * number * / int L, / * left * / int R & lt / * Right * / ) // for node No. P prepared for the two child nodes 2 * P, 2 * P +. 1 
16  {
 . 17     if(l==r) {tree[P]=a[l]; return ;}
18     int mid=(l+r)/2;
19     buildtree(P*2,l,mid);
20     buildtree(P*2+1,mid+1,r);
21     tree[P]=tree[P*2]+tree[P*2+1];
22 }//建树 已理解
23 void modifytree(int P,int l,int r,int ll,int rr,int x)//ll to rr plus X; ll \ rr is being modified interval around end 
24  {
 25      IF (L == ll && R & lt == rr) {Tree [P] + = X * (R & lt-L + . 1 ); the lazy [P] + = X; / * the lazy marked * /  return ;}
 26 is      pushdown (P, L, R & lt);
 27      int MID = (L + R & lt) / 2 ;
 28      IF (LL> MID) modifytree (P * 2 + . 1 , MID + . 1 , R & lt, LL, RR, X);
 29      the else  IF (MID> = RR) modifytree (P * 2 , L, MID, LL, RR, X);
 30      the else modifytree (P * 2 , L, MID, LL, MID, X), modifytree (P * 2 + . 1, MID + . 1 , R & lt, MID + . 1 , RR, X);
 31 is      Tree [P] = Tree [P * 2 ] + Tree [P * 2 + . 1 ];
 32  }
 33 is  Long  Long asktree / * Ask * / ( int P , int l, int r, int askl, int askr)
 34 is  // the number is P, the line segment l in the range of r, find askl askr to this section 
35  {
 36      int MID = (l + r) / 2 ;
 37 [      IF (R & lt == L == askl && askr) return Tree [P];
38     if(lazy[P]!=0) {
39         pushdown(P,l,r);}
40     
41     if(mid>=askr) return asktree(P*2,l,mid,askl,askr) ;
42     else if(mid<askl) return asktree(P*2+1,mid+1,r,askl,askr);
43     return asktree(P*2,l,mid,askl,mid)+asktree(P*2+1,mid+1,r,mid+1,askr);
44     
45 }
46 int main()
47 {
48     scanf("%lld %lld",&n,&m);
49     for(int i=1;i<=n;i++) scanf("%lld",&a[i]);
50     buildtree(1,1,n);
51     //scanf("%d",&m);
52     for(int i=1;i<=m;i++)
53     {
54     scanf("%lld",&x);
55     if(x==1) scanf("%lld %lld %lld",&y,&z,&d),modifytree(1,1,n,y,z,d);
56     if(x==2) scanf("%lld %lld",&y,&z),printf("%lld\n",asktree(1,1,n,y,z));
57     }
58     return 0; 
59 }

 

Guess you like

Origin www.cnblogs.com/liuziwen0224/p/tree1.html