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
题目大意
对于一个长度为N的数组支持两种操作,Q代表查询区间[l,r]的数的和;C代表将区间[l,r]内的数全部增加c.
解题思路
将每一个数都更新到叶子结点会超时
每个节点增加一个mark变量标记增量的累加
代码实现
#include<iostream>
#include<cstdio>
using namespace std;
#define ll long long
#define maxn 200007
struct node
{
int left;
int right;
ll value;
ll mark;
}tree[maxn<<2];
int num[maxn];
ll sum;
void create(int root,int l,int r)
{
tree[root].left=l;
tree[root].right=r;
tree[root].mark=0;
if(l==r)
{
tree[root].value=num[l];
return ;
}
int mid=(l+r)/2;
create(root*2,l,mid);
create(root*2+1,mid+1,r);
tree[root].value=tree[root*2].value+tree[root*2+1].value;
}
void Add(int root,int l,int r,ll v)
{
// if(l==tree[root].left&&tree[root].right==r)
if(tree[root].left==l&&tree[root].right==r)
{
// printf("##%d\n",tree[root].value);
tree[root].mark+=v;
return;
}
tree[root].value+=v*(r-l+1);
int mid=(tree[root].left+tree[root].right)/2;
if(r<=mid) Add(root*2,l,r,v);
else if(l>mid) Add(root*2+1,l,r,v);
else
{
Add(root*2,l,mid,v);
Add(root*2+1,mid+1,r,v);
}
}
ll query(int root,int l,int r)
{
if(l==tree[root].left&&tree[root].right==r)
return tree[root].value+(r-l+1)*tree[root].mark;
tree[root].value+=(tree[root].right-tree[root].left+1)*tree[root].mark;
int mid=(tree[root].left+tree[root].right)/2;
Add(root*2,tree[root].left,mid,tree[root].mark);
Add(root*2+1,mid+1,tree[root].right,tree[root].mark);
tree[root].mark=0;
if(r<=mid) return query(root*2,l,r);
else if(l>mid) return query(root*2+1,l,r);
else return query(root*2,l,mid)+query(root*2+1,mid+1,r);
}
int main()
{
int n,m;
int a,b,v;
char ch;
scanf("%d %d",&n,&m);
for(int i=1;i<=n;i++)
scanf("%d",&num[i]);
create(1,1,n);
getchar();
while(m--)
{
scanf("%c %d %d%*c",&ch,&a,&b);
if(ch=='Q')
printf("%I64d\n",query(1,a,b));
else
{
scanf("%d%*c",&v);
Add(1,a,b,v);
}
}
return 0;
}