CSP_JAKME @ 2024-10-18 21:43:07
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
int n,m,a[maxn],tree[maxn*4];
int lzy[maxn*4];
void pushup(int u){
tree[u]=tree[u*2]+tree[u*2+1];
}
void build(int u,int left,int right){
if(left==right){
tree[u]=a[left];
return;
}
int mid=(left+right)/2;
build(u*2,left,mid);
build(u*2+1,mid+1,right);
pushup(u);
return;
}
bool intheline(int L,int R,int l,int r){
return l<=L&&r>=R;
}
bool cdline(int L,int R,int l,int r){
return L<=r&&R>=l;
}
int sum(int u,int left,int right,int l,int r){
if(intheline(left,right,l,r)) return tree[u];
else if(cdline(left,right,l,r)){
int mid=(left+right)/2;
return sum(u*2,left,mid,l,r)+sum(u*2+1,mid+1,right,l,r);
}
return 0;
}
void make(int u,int k,int len){
lzy[u]+=k;
tree[u]+=len*k;
return;
}
void pushdown(int u,int left,int right){
int mid=(left+right)/2;
make(u*2,lzy[u],mid-left+1);
make(u*2+1,lzy[u],right-mid);
lzy[u]=0;
return;
}
/*
void printt(int u){
if(u>2*n-1) return;
cout << tree[u] << " ";
printt(u*2);
printt(u*2+1);
}
*/
void update(int u,int left,int right,int l,int r,int k){
if(intheline(left,right,l,r)){
make(u,k,right-left+1);
return;
}else if(cdline(left,right,l,r)){
int mid=(left+right)/2;
pushdown(u,left,right);
update(u*2,left,mid,l,r,k);
update(u*2+1,mid+1,right,l,r,k);
pushup(u);
}else return;
}
int main(){
cin >> n >> m;
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
build(1,1,n);
for(int i=1;i<=m;i++){
int opt,x,y;
cin >> opt >> x >> y;
if(opt==1){
int k;
cin >> k;
update(1,1,n,x,y,k);
}else{
printf("%d\n",sum(1,1,n,x,y));
}
}
return 0;
}
样例第4个操作直接改了根节点
by __A___ @ 2024-10-18 21:49:12
我们一般叫这个segment tree
by CSP_JAKME @ 2024-10-18 21:50:03
@__A___ haode
by yanyan2 @ 2024-10-18 21:51:23
@CSP_JAKME 给楼主一个建议,就是学模板的时候最好不要根据自己的理解 yy 一个出来,最好是对着别人的代码抄一遍
by CSP_JAKME @ 2024-10-18 21:52:32
@yanyan2 我是深入浅出看的
by 沐咕 @ 2024-10-18 21:55:48
@CSP_JAKME 深基还是深进(话说深进这名字取得……难评)
by yanyan2 @ 2024-10-18 21:57:30
@CSP_JAKME 直接操作根节点没问题吧,毕竟相当于是全局修改
by yanyan2 @ 2024-10-18 21:58:21
@CSP_JAKME 为啥不直接交呢
by CSP_JAKME @ 2024-10-18 21:59:20
@沐咕 深进
by CSP_JAKME @ 2024-10-18 22:01:21
@yanyan2 我很好奇你有没有学过线段树
by yanyan2 @ 2024-10-18 22:06:07
@CSP_JAKME 学过啊