Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 12302 | Accepted: 2958 | |
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
#include<stdio.h>
#define LL(x) (x<<1)
#define RR(x) (x<<1|1)
struct Seg_tree
{
int left,right;
__int64 sum,add;//用于标记下传,否则必TLE
int clamid() { return (left+right)/2; }
}tree[100001*3];
int num[100001];
int n,q;
void build(int l,int r,int idx)
{
tree[idx].left=l;
tree[idx].right=r;
tree[idx].add=0;
if(l==r)
{
tree[idx].sum=num[l];
return ;
}
int mid=tree[idx].clamid();
build(l,mid,LL(idx));
build(mid+1,r,RR(idx));
tree[idx].sum=tree[LL(idx)].sum+tree[RR(idx)].sum;
}
void Update(int l,int r,int idx,int c)
{
if(l<=tree[idx].left&&r>=tree[idx].right)
{
tree[idx].add+=c;
tree[idx].sum+=c*(tree[idx].right-tree[idx].left+1);
return ;
}
if(tree[idx].add)
{
tree[LL(idx)].add+=tree[idx].add;
tree[LL(idx)].sum+=tree[idx].add*(tree[LL(idx)].right-tree[LL(idx)].left+1);
tree[RR(idx)].add+=tree[idx].add;
tree[RR(idx)].sum+=tree[idx].add*(tree[RR(idx)].right-tree[RR(idx)].left+1);
tree[idx].add=0;
}
int mid=tree[idx].clamid();
if(r>mid) Update(l,r,RR(idx),c);
if(l<=mid) Update(l,r,LL(idx),c);
/*if(r>mid) Update(mid+1,r,RR(idx),c);
if(l<=mid) Update(l,mid,LL(idx),c);这是错误的*/
tree[idx].sum=tree[LL(idx)].sum+tree[RR(idx)].sum;
}
__int64 query(int l,int r,int idx)
{
if(l<=tree[idx].left&&r>=tree[idx].right)
return tree[idx].sum;
if(tree[idx].add)
{
tree[LL(idx)].add+=tree[idx].add;
tree[LL(idx)].sum+=tree[idx].add*(tree[LL(idx)].right-tree[LL(idx)].left+1);
tree[RR(idx)].add+=tree[idx].add;
tree[RR(idx)].sum+=tree[idx].add*(tree[RR(idx)].right-tree[RR(idx)].left+1);
tree[idx].add=0;
}
int mid=tree[idx].clamid();
if(r<=mid) return query(l,r,LL(idx));
else
if(l>mid) return query(l,r,RR(idx));
else
return query(l,mid,LL(idx))+query(mid+1,r,RR(idx));
}
int main()
{
while(scanf("%d%d",&n,&q)!=EOF)
{
for(int i=1;i<=n;i++) scanf("%d",&num[i]);
build(1,n,1);
for(int i=1;i<=q;i++)
{
char str[10];
int a,b,c;
scanf("%s",str);
if(str[0]=='Q')
{
scanf("%d%d",&a,&b);
printf("%I64d/n",query(a,b,1));
}
else
{
scanf("%d%d%d",&a,&b,&c);
Update(a,b,1,c);
}
}
}
return 0;
}