#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
空间限制: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和其他信息送回子区间。