luogu P3372 线段树1模板

Posted Misaka_Azusa

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了luogu P3372 线段树1模板相关的知识,希望对你有一定的参考价值。

线段树的模板题

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模板的主要内容,如果未能解决你的问题,请参考以下文章

Luogu P3372 模板线段树 1

luogu P3372 线段树1模板

luogu P3372 模板线段树 1

洛谷P3372线段树模板1——线段树

模板线段树(luogu P3372)

luogu P3372ybtoj线段树课堂过关例题2区间查改 &模板线段树 1