洛谷 P3372 【模板】线段树 1 题解 && 线段树模板

 题目

题目-【模板】线段树 1 - 洛谷

题目描述

如题,已知一个数列,你需要进行下面两种操作:

  1. 将某区间每一个数加上 𝑘。
  2. 求出某区间每一个数的和。

输入格式 

第一行包含两个整数 𝑛,𝑚,分别表示该数列数字的个数和操作的总个数。

第二行包含 𝑛 个用空格分隔的整数,其中第 𝑖 个数字表示数列第 𝑖 项的初始值。

接下来 𝑚 行每行包含 3 或 4 个整数,表示一个操作,具体如下:

  1. 1 x y k:将区间 [𝑥,𝑦] 内每个数加上 𝑘。
  2. 2 x y:输出区间 [𝑥,𝑦] 内每个数的和。

输出格式 

 输出包含若干行整数,即为所有操作 2 的结果。

代码 

 

#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N=1e5+10;
int n,m,a[N],op;
struct node{
	int l,r,sum,lazy;
}tree[4*N];
void pushup(int p){
	tree[p].sum=tree[2*p].sum+tree[2*p+1].sum;
}
void build(int p,int l,int r){
	tree[p].l=l;
	tree[p].r=r;
	tree[p].sum=tree[p].lazy=0;
	if(l==r){
		tree[p].sum=a[l];
		return ;
	}
	int mid=(l+r)/2;
	build(2*p,l,mid);
	build(2*p+1,mid+1,r);
	pushup(p);
}
void pushdown(int p){
	tree[2*p].lazy+=tree[p].lazy;
	tree[2*p+1].lazy+=tree[p].lazy;
	tree[2*p].sum+=(tree[2*p].r-tree[2*p].l+1)*tree[p].lazy;
	tree[2*p+1].sum+=(tree[2*p+1].r-tree[2*p+1].l+1)*tree[p].lazy;
	tree[p].lazy=0;
}
void update(int p,int l,int r,int k){
	if(tree[p].l>r||tree[p].r<l){
		return ;
	}
	if(tree[p].l>=l&&tree[p].r<=r){
		tree[p].sum+=(tree[p].r-tree[p].l+1)*k;
		tree[p].lazy+=k;
		return ;
	}
	if(tree[p].lazy) pushdown(p);
	update(2*p,l,r,k);
	update(2*p+1,l,r,k);
	pushup(p);
}
int query(int p,int l,int r){
	if(tree[p].l>r||tree[p].r<l){
		return 0;
	}
	if(tree[p].l>=l&&tree[p].r<=r){
		return tree[p].sum;
	}
	if(tree[p].lazy) pushdown(p);
	return query(2*p,l,r)+query(2*p+1,l,r);
}
signed main(){
	cin>>n>>m;
	for(int i=1;i<=n;i++){
		cin>>a[i];
	}
	build(1,1,n);
	for(int i=1;i<=m;i++){
		cin>>op;
		int x,y,k;
		cin>>x>>y;
		if(op==1){
			cin>>k;
			update(1,x,y,k);
		}
		else{
			cout<<query(1,x,y)<<endl;
		}
	}
	return 0;
}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值