线段树区间修改入门

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
int tree[4*maxn],lazy[4*maxn],a[maxn];
void update(int p){
	tree[p]=tree[p<<1]+tree[p<<1|1];
}
void pushdown(int p,int lenl,int lenr)
{
	if(lazy[p])
	{
		lazy[p<<1]+=lazy[p];
		lazy[p<<1|1]+=lazy[p];
		tree[p<<1]+=lenl*lazy[p];
		tree[p<<1|1]+=lenr*lazy[p];
		lazy[p]=0;
	}	
}
void add(int l,int r,int x,int y,int p,int v)
{
	if(l>=x&&r<=y){
		lazy[p]+=v;
		tree[p]+=(r-l+1)*v;
		return;
	}
	int mid=(l+r)>>1;
	pushdown(p,mid-l+1,r-mid);
	if(mid>=x) add(l,mid,x,y,p<<1,v);
	if(mid<y)  add(mid+1,r,x,y,p<<1|1,v);
	update(p);
}
int query(int l,int r,int x,int y,int p)
{//当用到这一层的时候,将lazy消除并传递给下一层 
	if(l>=x&&r<=y) return tree[p];
	int mid=(l+r)>>1;int res=0;
	pushdown(p,mid-l+1,r-mid);
	if(mid>=x) res+=query(l,mid,x,y,p<<1);
	if(mid<y)  res+=query(mid+1,r,x,y,p<<1|1);
	return res;
}
void build(int l,int r,int p){
	lazy[p]=0;
	if(l==r) {tree[p]=a[l];return;}
	int mid=(l+r)>>1;
	build(l,mid,p<<1);
	build(mid+1,r,p<<1|1);
	update(p);
}
int main()
{
	int n,m;cin>>n>>m;
	for(int i=1;i<=n;i++)
		cin>>a[i];
	build(1,n,1);
	char c;int a,b,v;
	for(int i=1;i<=m;i++)
	{
		cin>>c;
		if(c=='Q')
		{
			cin>>a>>b;
			int ans=query(1,n,a,b,1);
			cout<<ans<<endl;
		}
		else {
			cin>>a>>b>>v;
			add(1,n,a,b,1,v);
		}
	}
	return 0;
} 


Lazy


区间成段更新

Lazy:正常来说,区间改值,当更改某个区间的值的时候,子区间也该跟着更改,这样容易TLE。

Lazy思想就是更新到某个区间的时候,就先给这个区间打上标记,标记内容是需要更新的值,并把子区间的值改为子区间对应的值,清除该区间的lazy标记;然后return,不去更新子区间。当下一次更新或查询等需要访问该区间的子区间的时候再把该区间的lazy和其他信息送回子区间。


链接: https://www.nowcoder.com/acm/contest/77/H
来源:牛客网

Tree Recovery
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 131072K,其他语言262144K
64bit IO Format: %lld

题目描述

You have  N  integers,  A 1 A 2 , ... ,  AN . You need to deal with two kinds of operations. One type of operation is to add some given number to each number in a given interval. The other is to ask for the sum of numbers in a given interval.

输入描述:

The first line contains two numbers N and Q. 1 ≤ N,Q ≤ 100000.
The second line contains N numbers, the initial values of A1, A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of Aa, Aa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of Aa, Aa+1, ... , Ab.

输出描述:

You need to answer all Q commands in order. One answer in a line.
Lazy


区间成段更新

Lazy:正常来说,区间改值,当更改某个区间的值的时候,子区间也该跟着更改,这样容易TLE。

Lazy思想就是更新到某个区间的时候,就先给这个区间打上标记,标记内容是需要更新的值,并把子区间的值改为子区间对应的值,清除该区间的lazy标记;然后return,不去更新子区间。当下一次更新或查询等需要访问该区间的子区间的时候再把该区间的lazy和其他信息送回子区间。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值