ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

线段树

2022-08-20 18:05:03  阅读:126  来源: 互联网

标签:rt ll int 线段 ans query scanf


https://www.luogu.com.cn/problem/P3372

 1 #include <iostream>
 2 #include <cstdio>
 3 using namespace std;
 4 #define lson l,mid,rt<<1
 5 #define rson mid+1,r,rt<<1|1 
 6 #define ll long long
 7 const int mac=1e5+50;
 8 ll tree[mac<<2],a[mac];
 9 ll lazy[mac<<2];
10 void push_up(int rt){
11     tree[rt]=tree[rt<<1]+tree[rt<<1|1];
12 }
13 void push_down(int l,int r,int rt){
14     if(lazy[rt]!=0){
15         int mid=(l+r)>>1;
16         tree[rt<<1]+=lazy[rt]*(mid-l+1);
17         tree[rt<<1|1]+=lazy[rt]*(r-mid);
18         lazy[rt<<1]+=lazy[rt];
19         lazy[rt<<1|1]+=lazy[rt];
20         lazy[rt]=0;
21     }
22 }
23 void build(int l,int r,int rt){
24     if(l==r){
25         scanf("%lld",&tree[rt]);
26         return ;
27     }
28     int mid=(l+r)>>1;
29     build(lson);
30     build(rson);
31     push_up(rt);
32 }
33 ll query(int l,int r,int rt,int L,int R,ll ans){
34     if(r<L||l>R)
35         return ans;
36     if(l>=L&&r<=R){
37         return ans+tree[rt];
38     }
39     push_down(l,r,rt);
40     int mid=(l+r)>>1;
41     if(L<=mid){
42         ans=query(lson,L,R,ans);
43     }
44     if(R>mid){
45         ans=query(rson,L,R,ans);
46     }
47     return ans;
48 }
49 void update(int l,int r,int rt,int L,int R,ll z){
50     if(l>R||r<L)
51         return;
52     if(l>=L&&r<=R){
53         tree[rt]+=(r-l+1)*z;
54         lazy[rt]+=z;
55         return ;
56     }
57     push_down(l,r,rt);
58     int mid=(l+r)>>1;
59     if(L<=mid){
60         update(lson,L,R,z);
61     }
62     if(R>mid){
63         update(rson,L,R,z);
64     }
65     push_up(rt);
66 }
67 int main(){
68     int i,n,m,k,x,y;
69     ll ans=0,z;
70     scanf("%d %d",&n,&m);
71     build(1,n,1);
72     while(m--){
73         scanf("%d",&k);
74         switch(k){
75             case 1:{
76                 scanf("%d %d %lld",&x,&y,&z);
77                 update(1,n,1,x,y,z);
78                 break;
79             }
80             case 2:{
81                 scanf("%d %d",&x,&y);
82                 ans=query(1,n,1,x,y,ans);
83                 printf("%lld\n",ans);
84                 ans=0;
85                 break;
86             }
87         }
88     }
89 }
View Code

 

标签:rt,ll,int,线段,ans,query,scanf
来源: https://www.cnblogs.com/hcl6/p/16608245.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有