模板

本文最后更新于:2023年11月7日 下午

数据结构

线段树1

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
64
65
66
67
68
69
70
71
72
73
#include<cstdio>
#include<iostream>
using namespace std;
const int maxn=1e5+10;
int n,m;
long long a[maxn];
long long tree[4*maxn];
long long tag[4*maxn];
void build(int p,int l,int r){
if(l==r){
tree[p]=a[l];
return;
}
int mid=(l+r)>>1;
build(p*2,l,mid);
build(p*2+1,mid+1,r);
tree[p]=tree[p*2]+tree[p*2+1];
}
void spread(int p,int l,int r){
if(tag[p]){
int mid=(l+r)>>1;
int lson=p*2,rson=lson+1;
tag[lson]+=tag[p];
tree[lson]+=tag[p]*(mid-l+1);
tag[rson]+=tag[p];
tree[rson]+=tag[p]*(r-mid);
tag[p]=0;
}
}
//注意这里的cl,cr为查询的区间,l和r为节点的区间
long long ask(int p,int cl,int cr,int l,int r){
// cout<<"dbg:"<<cl<<" "<<cr<<" "<<l<<" "<<r<<" "<<tree[p]<<endl;
if(cl<=l&&cr>=r)
return tree[p];
spread(p,l,r);
int mid=(l+r)>>1;
long long res=0;
if(cl<=mid) res+=ask(p*2,cl,cr,l,mid);
if(cr>mid) res+=ask(p*2+1,cl,cr,mid+1,r);
return res;
}
void change(int p,int d,int cl,int cr,int l,int r){
if(cl<=l&&cr>=r){
tag[p]+=d;
tree[p]+=d*(r-l+1);
return;
}
spread(p,l,r);
int mid=(l+r)>>1;
int lson=p*2,rson=lson+1;
if(cl<=mid) change(lson,d,cl,cr,l,mid);
if(cr>mid) change(rson,d,cl,cr,mid+1,r);
tree[p]=tree[lson]+tree[rson];
}
int main(){
scanf("%d%d",&n,&m);
long long opt,x,y,z;
for(int i=1;i<=n;i++)
scanf("%lld",&a[i]);
build(1,1,n);
for(int i=1;i<=m;i++){
scanf("%lld",&opt);
if(opt==1){
scanf("%lld%lld%lld",&x,&y,&z);
change(1,z,x,y,1,n);
}else{
scanf("%lld%lld",&x,&y);
printf("%lld\n",ask(1,x,y,1,n));
}
}
return 0;
}
// 1 7 6 2 3

模板
http://example.com/2023/06/15/模板/
作者
微分方程
发布于
2023年6月15日
许可协议