【luogu P3372 線段樹1】模板
阿新 • • 發佈:2018-02-28
esp algorithm n) col LG uil shu amp urn
線段樹的模板題
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】模板