线段树模板(入门。。。)
1.P3372
【模板】线段树1
#include <bits/stdc++.h>
#define int long long
#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r
using namespace std;
const int N = 1e5+10;
int tree[N<<2],lazy[N<<2];
int a[N];
inline void push_up(int rt)
{
tree[rt]=tree[rt<<1]+tree[rt<<1|1];
}
void build(int rt,int l,int r)
{
lazy[rt]=0;
if(l==r){
tree[rt]=a[l];
return;
}
int mid=l+r>>1;
build(lson),build(rson);
push_up(rt);
}
inline void push_down(int rt,int m)
{
if(!lazy[rt]) return ;
lazy[rt<<1]+=lazy[rt],lazy[rt<<1|1]+=lazy[rt];
tree[rt<<1]+=lazy[rt]*(m-(m>>1));
tree[rt<<1|1]+=lazy[rt]*(m>>1);
lazy[rt]=0;
}
// void update_single_point(int rt,int l,int r,int pos,int val)
// {
// if(l==r){
// tree[rt]=val;
// return;
// }
// int mid=l+r>>1;
// if(mid>=pos) update_single_point(lson,pos,val);
// else update_single_point(rson,pos,val);
// push_up(rt);
// }
void update_part(int rt,int l,int r,int L,int R,int val)
{
if(l>=L&&r<=R){
lazy[rt]+=val;
tree[rt]+=val*(r-l+1);
return;
}
push_down(rt,r-l+1);
int mid=l+r>>1;
if(mid>=L) update_part(lson,L,R,val);
if(mid<R) update_part(rson,L,R,val);
push_up(rt);
}
int query(int rt,int l,int r,int L,int R)
{
if(l>=L&&r<=R) return tree[rt];
push_down(rt, r-l+1);
int mid=l+r>>1,ans=0;
if(mid>=L) ans+=query(lson,L,R);
if(mid<R) ans+=query(rson,L,R);
return ans;
}
signed main(){
ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int n,m,op,sum=0; cin >> n >> m;
for(int i=1;i<=n;i++) cin >> a[i];
build(1,1,n);
while(m--){
int x,y,k;
cin >> op;
if(op==1){
cin >> x >> y >> k;
update_part(1,1,n,x,y,k);
}
else {
cin >> x >> y;
sum=query(1,1,n,x,y);
cout << sum << endl;
}
}
return 0;
}
u p d a t e _ s i n g l e _ p o i n t ( ) update\_single\_point() update_single_point() 是错的QAQ 因为可以通过区间修改函数来实现单点修改 所以这个函数可有可无…