A Simple Problem with Integers
Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 150462 | Accepted: 46648 | |
Case Time Limit: 2000MS |
Description
You have N integers, A1, A2, ... , 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.
Input
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.
Output
You need to answer all Q commands in order. One answer in a line.
Sample Input
10 5
1 2 3 4 5 6 7 8 9 10
Q 4 4
Q 1 10
Q 2 4
C 3 6 3
Q 2 4
Sample Output
4
55
9
15
题意:有一个数组,有两种操作。1: Q a b 求[a,b]的和 2:C a b c 给[a,b]的所有元素都加上c。
题解:区间求和加区间更新,典型的带懒惰标记的线段树。懒惰标记:更新的时候并不将每个元素都更新,而是将要更新的区间打上懒惰标记,等下次要使用的时候再向下更新。
#include<cstdio>
using namespace std;
const int maxn=1e5+7;
typedef long long ll;
ll tree[maxn<<2]; //线段树开4倍空间
int lazytag[maxn<<2]; //懒惰标记
int n,q,a,b,c;
char s[2];
void pushup(int now) //维护信息
{
tree[now]=tree[now<<1]+tree[now<<1|1];
return ;
}
void build_tree(int l,int r,int now) //建树
{
lazytag[now]=0; // 建树时 将懒惰标记的值初始化为0
if(l==r){
scanf("%lld",&tree[now]);
return ;
}
int mid=(l+r)/2;
build_tree(l,mid,now<<1);
build_tree(mid+1,r,now<<1|1);
pushup(now);
}
void pushdown(int l,int r,int now) //将懒惰标记向下更新
{
if(lazytag[now]!=0){
lazytag[now<<1]+=lazytag[now];
lazytag[now<<1|1]+=lazytag[now];
int width=r-l+1;
tree[now<<1|1]+=(ll)(width>>1)*lazytag[now];
//int 向下取整 右子树的长度小于等于左子树的长度
tree[now<<1]+=(ll)(width-(width>>1))*lazytag[now];
//左子树长度等于总长度减去右子树长度
lazytag[now]=0;
}
return ;
}
void update(int L,int R,int v,int l,int r,int now)
{
if(L<=l&&r<=R){
lazytag[now]+=v;
tree[now]+=(r-l+1)*v;
return ;
}
pushdown(l,r,now);
int mid=(l+r)>>1;
if(L<=mid) update(L,R,v,l,mid,now<<1);
if(R>mid) update(L,R,v,mid+1,r,now<<1|1);
pushup(now);
}
ll query(int ql,int qr,int l,int r,int now)
{
if(ql<=l&&r<=qr){
return tree[now];
}
pushdown(l,r,now);
ll ans=0;
int mid=(l+r)>>1;
if(ql<=mid) ans+=query(ql,qr,l,mid,now<<1);
if(qr>mid) ans+=query(ql,qr,mid+1,r,now<<1|1);
return ans;
}
int main()
{
while(scanf("%d %d",&n,&q)==2){
build_tree(1,n,1);
for(int i=1;i<=q;i++){
scanf("%s",s);
if(s[0]=='Q'){
scanf("%d %d",&a,&b);
printf("%lld\n",query(a,b,1,n,1));
}
else if(s[0]=='C') {
scanf("%d %d %d",&a,&b,&c);
update(a,b,c,1,n,1);
}
}
}
return 0;
}