蒟蒻刚学线段树1ms WA+RE求助
查看原帖
蒟蒻刚学线段树1ms WA+RE求助
1290709
__muiceredipS_楼主2024/10/21 22:19
#include<bits/stdc++.h>
#define open(x) freopen(#x".in","r",stdin),freopen(#x".out","w",stdout)
using namespace std;
long long tree[400005];
long long b[400005];
long long a[100005];
int n,m;
void build(int s,int t,int p){
	if (s==t){
		tree[p]=a[s];
		return ;
	}
	long long m=s+t>>1;
	build(s,m,p<<1),build(m+1,t,p<<1+1);
	tree[s]=tree[s<<1]+tree[s<<1+1];
	return ;
}
void update(int &l,int &r,int c,int s,int t,int p){
	if (l<=s&&r>=t){
		tree[p]+=(t-s+1)*c,b[p]+=c;
		return ;
	}
	long long m=s+t>>1;
	if (b[p]!=0&&s!=t){
		tree[p<<1]+=(m-s+1)*b[p],b[p<<1]+=b[p];
		tree[p<<1+1]+=(t-m)*b[p],b[p<<1+1]+=b[p];
		b[p]=0;
	}
	if (l<=m)
		update(l,r,c,s,m,p<<1);
	if (r>m)
		update(l,r,c,m+1,t,p<<1);
	tree[p]=tree[p<<1]+tree[p<<1+1];
}
long long query(int &l,int &r,int s,int t,int p){
	if (l<=s&&r>=t)
		return tree[p];
	long long m=s+t>>1,sum=0;
	if (b[p]!=0){
		tree[p<<1]+=(m-s+1)*b[p],b[p<<1]+=b[p];
		tree[p<<1+1]+=(t-m)*b[p],b[p<<1+1]+=b[p];
		b[p]=0;
	}
	if (l<=m)
		sum+=query(l,r,s,m,p<<1);
	if (r>m)
		sum+=query(l,r,m+1,t,p<<1+1);
	return sum;
}
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
	cin>>n>>m;
	for (int i=1;i<=n;i++)
		cin>>a[i];
	build(1,n,1);
	for (int i=1;i<=m;i++){
		int op,x,y,k;
		cin>>op>>x>>y;
		if (op==1){
			cin>>k;
			update(x,y,k,1,n,1);
		}
		else
			cout<<query(x,y,1,n,1)<<endl;
	}
	return 0;
}
2024/10/21 22:19
加载中...