A Simple Problem with Integers【线段树】

题解

线段树的模板题,注意好好理解一下lazytag:假如对 [1,5] 区间 +1,那可以在线段树[1,4]这个位置打一个标记,不继续递归往下更新,直到需要修改或查询它的儿子结点

#include<iostream>
#include<sstream>
#include<string>
#include<queue>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include <utility>
#include<list>
#include<bitset>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<iomanip>
#include<time.h>
using namespace std;

#define int long long
#define PI acos(-1.0)
#define eps 1e-9
#define lowbit(a) ((a)&-(a))

const int mod = 1e9+7;
int qpow(int a,int b,int ans=1){
	do{
		if(b&1)ans=(ans*a)%mod;
		a=(a*a)%mod;
	}while(b>>=1);
	return ans;
}
const int INF = 0x3f3f3f3f;
const int N = 1e6+10;

int n,a[N];
struct node{
	int l,mid,r;
	int val,tag;
}seg[N];
void pushup(int rt){
	seg[rt].val=seg[rt<<1].val+seg[rt<<1|1].val;
}
void pushdown(int rt){
	seg[rt<<1].val+=seg[rt].tag*(seg[rt<<1].r-seg[rt<<1].l+1); seg[rt<<1].tag+=seg[rt].tag;
	seg[rt<<1|1].val+=seg[rt].tag*(seg[rt<<1|1].r-seg[rt<<1|1].l+1); seg[rt<<1|1].tag+=seg[rt].tag;
	seg[rt].tag=0;
}
void build(int rt,int l,int r){
	int mid=l+r>>1;
	seg[rt].l=l , seg[rt].r=r , seg[rt].mid=mid , seg[rt].tag=0;
	if(l==r) { seg[rt].val=a[l]; return ;}
	build(rt<<1,l,mid); build(rt<<1|1,mid+1,r);
	pushup(rt);
}
void update(int rt,int l,int r,int val){
	if(seg[rt].l>=l&&seg[rt].r<=r) { seg[rt].val+=val*(seg[rt].r-seg[rt].l+1); seg[rt].tag+=val; return;}
	pushdown(rt);
	if(l<=seg[rt].mid) update(rt<<1,l,r,val);
	if(r>seg[rt].mid) update(rt<<1|1,l,r,val);
	pushup(rt);
}
int query(int rt,int l,int r){
	if(seg[rt].l>r||seg[rt].r<l) return 0;
	if(seg[rt].l>=l&&seg[rt].r<=r) return seg[rt].val;
	pushdown(rt);
	int ans=0;
	if(l<=seg[rt].mid) ans+=query(rt<<1,l,r);
	if(r>seg[rt].mid) ans+=query(rt<<1|1,l,r);
	return ans;
}
#define endl '\n'
signed main(){
	std::ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);
	int n,q; cin>>n>>q;
	for(int i=1;i<=n;i++)cin>>a[i]; 
	build(1,1,n);
	while(q--){
		string op; cin>>op;
		if(op=="Q"){
			int l,r; cin>>l>>r;
			cout<<query(1,l,r)<<endl;
		}
		else{
			int l,r,add; cin>>l>>r>>add;
			update(1,l,r,add);
		}
	}	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值