Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 74705 | Accepted: 22988 | |
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
Hint
Source
题目意思:给定Q (1 ≤ Q ≤ 100,000)个数A1,A2 … AQ,, 以及可能多次进行的两个操作:
1)对某个区间Ai … Aj的每个数都加n(n可变) 2) 求某个区间Ai … Aj的数的和。
就是线段树的更新与查询操作,这里要用到延迟更新。
注意sum和add都要设成int64型,因为在更新过程中,add也可能会因为累加而超出int型的范围。
#include<stdio.h>
#include<string.h>
#define M 100005
struct tree{
int l,r;
__int64 sum,add;
}tree[M<<2];
void pushup(int root)
{
if(tree[root].l==tree[root].r)return;
tree[root].sum=tree[root<<1].sum+tree[root<<1|1].sum;
return;
}
void pushdown(int root)
{
if(tree[root].l==tree[root].r)return;
if(tree[root].add==0)return;
tree[root<<1].add+=tree[root].add;
tree[root<<1|1].add+=tree[root].add;
tree[root<<1].sum=tree[root<<1].sum+(tree[root<<1].r-tree[root<<1].l+1)*tree[root].add;
tree[root<<1|1].sum=tree[root<<1|1].sum+(tree[root<<1|1].r-tree[root<<1|1].l+1)*tree[root].add;
tree[root].add=0;
return;
}
void build(int l,int r,int root)
{
tree[root].l=l;
tree[root].r=r;
tree[root].sum=0;
tree[root].add=0;
if(l==r){
tree[root].sum=0;
return;
}
int mid=l+r>>1;
build(l,mid,root<<1);
build(mid+1,r,root<<1|1);
pushup(root);
}
void update(int l,int r,int root,__int64 z)
{
if(tree[root].l==l&&tree[root].r==r)
{
tree[root].sum=tree[root].sum+(r-l+1)*z;
tree[root].add=tree[root].add+z; //有可能出现多次的更新操作,所以要将所有的add都累加起来。
return;
}
pushdown(root);
int mid=tree[root].l+tree[root].r>>1;
if(r<=mid)update(l,r,root<<1,z);
else if(l>mid)update(l,r,root<<1|1,z);
else {
update(l,mid,root<<1,z);
update(mid+1,r,root<<1|1,z);
}
pushup(root);
return;
}
__int64 Query(int l,int r,int root)
{
if(l==tree[root].l&&r==tree[root].r){
return tree[root].sum;
}
pushdown(root);
int mid=tree[root].l+tree[root].r>>1;
if(r<=mid)return Query(l,r,root<<1);
else if(l>mid)return Query(l,r,root<<1|1);
else {
return Query(l,mid,root<<1)+Query(mid+1,r,root<<1|1);
}
}
int main()
{
int N,Q,i,j,k,a,b;
__int64 c,d;
char s[20];
while(scanf("%d%d",&N,&Q)!=EOF)
{
build(1,N,1);
for(i=1;i<=N;i++)
{
scanf("%I64d",&d);
update(i,i,1,d);
}
while(Q--)
{
scanf("%s%d%d",s,&a,&b);
if(s[0]=='Q'){
printf("%I64d\n",Query(a,b,1));
}
if(s[0]=='C'){
scanf("%I64d",&c);
update(a,b,1,c);
}
}
}
return 0;
}