[模板]线段树

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=200000+5;
inline ll readll()
{
char c;ll x=1,tmp=0;c=getchar();
while(!isdigit(c)){if(c=='-') x=-1;c=getchar();}
while(isdigit(c)){tmp=tmp*10+c-'0';c=getchar();}
return tmp*x;
}
ll sumv[maxn*10],addv[maxn*10],a[maxn],n,m,x[maxn],y[maxn];
#define mid l+(r-l)/2
#define lson o*2
#define rson o*2+1
void getadd(int o,int l,int r,ll ad){addv[o]+=ad;sumv[o]+=ad*(r-l+1);}
void maintain(int o,int l,int r){sumv[o]=sumv[lson]+sumv[rson]+addv[o]*(r-l+1);}
void pushdown(int o,int l,int r)
{
if(addv[o]!=0)
{
getadd(lson,l,mid,addv[o]);
getadd(rson,mid+1,r,addv[o]);
addv[o]=0;
maintain(o,l,r);
}
}
void update(int o,int l,int r ,int ql,int qr,ll ad)
{
if(ql>r || qr<l) return;
if(ql<=l && r<=qr) {getadd(o,l,r,ad);return;}
pushdown(o,l,r);
if(ql<=mid) update(lson,l,mid,ql,qr,ad);
if(qr>mid) update(rson,mid+1,r,ql,qr,ad);
maintain(o,l,r);
}
ll query(int o,int l,int r,int ql,int qr)
{
if(ql>r || qr<l) return 0;
if(ql<=l && r<=qr) return sumv[o];
pushdown(o,l,r);
ll sum=0;
if(ql<=mid) sum+=query(lson,l,mid,ql,qr);
if(qr>mid) sum+=query(rson,mid+1,r,ql,qr);
return sum;
}
int main()
{
scanf("%lld%lld",&n,&m);
for(int i=1;i<=n;i++) update(1,1,n,i,i,readll());
int op,l,r;
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&op,&l,&r);
if(op==2){
printf("%lld\n",query(1,1,n,l,r));
}else{
ll num=readll();
update(1,1,n,l,r,num);
}
}
return 0;
}