跳到正文

剪贴板

剪贴板 go4rz5e4

原文
剪贴板信息

剪贴板信息

收录
更新

线段树

C++
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N=1e5+10;
int ls(int p) {return p<<1;}
int rs(int p) {return p<<1|1;}
struct node{
	int l,r,sum;
}tree[N<<2];
int tag[N<<2];
int k[N];
void push_up(int p) {
	tree[p].sum=tree[ls(p)].sum+tree[rs(p)].sum;
}
void add_tag(int p,int l,int r,int d){
	tag[p]+=d;
	tree[p].sum+=d*(r-l+1);
}//Lazy_Tag标记
void push_down(int p){
	if (tag[p]){
		int mid=(tree[p].l+tree[p].r)>>1;
		add_tag(ls(p),tree[p].l,mid,tag[p]);
		add_tag(rs(p),mid+1,tree[p].r,tag[p]);
		tag[p]=0;
	}
}
void update(int l,int r,int p,int d){
	if (l<=tree[p].l && tree[p].r<=r){
		add_tag(p,tree[p].l,tree[p].r,d);
		return ;
	}
	int mid=(tree[p].l+tree[p].r)>>1;
	push_down(p);
	if (l<=mid) update(l,r,ls(p),d);
	if (r>mid) update(l,r,rs(p),d);
	push_up(p);
}//区间修改
int query(int l,int r,int p){
	if (l<=tree[p].l && tree[p].r<=r) return tree[p].sum;
	int mid=(tree[p].l+tree[p].r)>>1;
	push_down(p);
	int ans=0;
	if (l<=mid) ans+=query(l,r,ls(p));
	if (r>mid) ans+=query(l,r,rs(p));
	return ans;
}//区间查询
void build(int p,int l,int r){
	tree[p]=(node){l,r,k[l]};
	tag[p]=0;
	if (l==r) return ;
	int mid=(l+r)>>1;
	build(ls(p),l,mid);
	build(rs(p),mid+1,r);
	push_up(p);
}//建树
int n,m,a,b,c,d;
signed main(){
	cin>>n>>m;
	for (int i=1;i<=n;i++) cin>>k[i];
	build(1,1,n);
	while (m--){
		cin>>a>>b>>c;
		if (a==1){
			cin>>d;
			update(b,c,1,d);
		}
		else{
			cout<<query(b,c,1)<<'\n';
		}
	}
    return 0;
}