码迷,mamicode.com
首页 > 其他好文 > 详细

【luogu P3372 线段树1】模板

时间:2018-02-28 18:56:45      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:bsp   cst   int   pushd   define   ==   cout   while   body   

线段树的模板题

update区间修改,query区间求和

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 #define ll long long
 5 #define lson left, mid, rt<<1
 6 #define rson mid+1, right, rt<<1|1
 7 using namespace std;
 8 const int maxn = 100000;
 9 ll n, m, ans[maxn<<2],lazy[maxn<<2],tot=0,re[maxn<<2];
10 void PushUP(ll rt)
11 {
12     ans[rt] = ans[rt<<1] + ans[rt<<1|1];
13 }
14 void build(ll left, ll right, ll rt)
15 {
16     if(left == right)
17     {
18         cin>>ans[rt];
19         return;
20     }
21     ll mid = (left + right)>>1;
22     build(lson);
23     build(rson);
24     PushUP(rt);
25 }
26 
27 void PushDOWN(ll rt, ll mid, ll left, ll right)
28 {
29     if(lazy[rt])
30     {
31         lazy[rt<<1]+=lazy[rt];
32         lazy[rt<<1|1]+=lazy[rt];
33         ans[rt<<1]+=(mid-left+1)*lazy[rt];
34         ans[rt<<1|1]+=(right-mid)*lazy[rt];
35         lazy[rt]=0;
36     }
37 }
38 ll query(ll l, ll r, ll left, ll right, ll rt)
39 {
40     ll res = 0;
41     if(l<=left&&r>=right)
42     {
43         return ans[rt];
44     }
45     ll mid = (left + right)>>1;
46     PushDOWN(rt,mid,left,right);
47     if(l<=mid) res += query(l,r,lson);
48     if(r>mid) res += query(l,r,rson);
49     return res;
50 }
51 void update(ll l, ll r, ll add, ll left, ll right, ll rt)
52 {
53     if(l<=left&&r>=right)
54     {
55         lazy[rt]+=add;
56         ans[rt]+=add*(right-left+1);
57         return;
58     }    
59     ll mid = (left+right)>>1;
60     PushDOWN(rt,mid,left,right);
61     if(l<=mid) update(l,r,add,lson);
62     if(r>mid)  update(l,r,add,rson);
63     PushUP(rt);
64 }
65 
66 int main()
67 {
68     cin.sync_with_stdio(false);
69     cin>>n>>m;
70     ll p,x,y,k;
71     build(1,n,1);
72     while(m--)
73     {
74         cin>>p;
75         if(p==1)
76         {
77             cin>>x>>y>>k; update(x,y,k,1,n,1);
78         }
79         if(p==2)
80         {
81             tot++;
82             cin>>x>>y;    cout<<query(x,y,1,n,1);
83         }
84     }
85     return 0;
86 }

 

【luogu P3372 线段树1】模板

标签:bsp   cst   int   pushd   define   ==   cout   while   body   

原文地址:https://www.cnblogs.com/MisakaAzusa/p/8485181.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!