[线段树]Luogu P3372 线段树 1【模板】

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>

#define type long long int
#define N (100000+2)

using namespace std;

type n,m;
type edge[N<<2];
type sum[N<<2];

void change(type &x,type &y,type &v,type l=1,type r=n,type k=1){
	if(r<x||y<l)
		return ;
	if(x<=l&&r<=y){
		sum[k]+=v;
		return ;
	}
	edge[k]+=(min(r,y)-max(l,x)+1)*v;
	register type mid=(l+r)>>1;
	if(x<=mid)
		change(x,y,v,l,mid,k<<1);
	if(mid<y)
		change(x,y,v,mid+1,r,(k<<1)+1);
	return ; 
}
type get(type &x,type &y,type l=1,type r=n,type k=1){
	if(r<x||y<l)
		return 0;
	if(x<=l&&r<=y)
		return edge[k]+(r-l+1)*sum[k];
	register type mid=(l+r)>>1;
	register type res=(min(r,y)-max(l,x)+1)*sum[k];
	if(x<=mid)
		res+=get(x,y,l,mid,k<<1);
	if(mid<y)
		res+=get(x,y,mid+1,r,(k<<1)+1);
	return res;
}

int main(){
	register type i,tmp,x,y,v;
	ios::sync_with_stdio(0);
	memset(edge,0,sizeof edge);
	memset(sum,0,sizeof sum);
	cin>>n>>m;
	for(i=1;i<=n;i++){
		cin>>v;
		change(i,i,v);
	}
	for(i=1;i<=m;i++){
		cin>>tmp>>x>>y;
		if(tmp==1){
			cin>>v;
			change(x,y,v);
		}
		else
		if(tmp==2){
			cout<<get(x,y)<<endl;
		}
	}
	return 0;
}
posted @ 2019-07-15 16:58  ты  阅读(118)  评论(0编辑  收藏  举报