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
The sums may exceed the range of 32-bit integers.
这题应该算是线段树区间修改的模板题了,一开始因为longlong没开wa了几发,ac了后又打了两遍,毕竟刚学线段树,增加熟练度
#include<iostream>
#include<stdio.h>
using namespace std;
const int MAXN = 100000 + 10;
struct f
{
long long len ;
long long val;
long long lazy;
}a[MAXN * 4];
int n , m ;
void pushup(int k)
{
a[k].val = a[k << 1].val + a[k << 1 | 1].val;
}
void pushdown(int x)
{
if(a[x].lazy)
{
a[x << 1].lazy += a[x].lazy;
a[x << 1 | 1].lazy += a[x].lazy;
a[x << 1].val += a[x << 1].len * a[x].lazy;
a[x << 1 | 1].val += a[x << 1 | 1].len * a[x].lazy;
a[x].lazy = 0;
}
}
void build(int left , int right , int rt)
{
a[rt].len = right - left + 1;
if(left == right)
{
scanf("%lld" , &a[rt].val);
return ;
}
int mid = (left + right) >> 1;
build(left , mid , rt << 1);
build(mid + 1 , right , rt << 1 | 1);
a[rt].val = a[rt << 1].val + a[rt << 1 | 1].val;
}
long long que(int x , int y ,int left , int right ,int rt)
{
if(left >= x && right <= y)
{
return a[rt].val;
}
if(a[rt].lazy)
{
pushdown(rt);
}
long long sum = 0;
int mid = (left + right) >> 1;
if(mid >= x)
sum += que(x , y , left , mid , rt << 1);
if(mid < y)
sum += que(x , y , mid + 1, right , rt << 1 | 1);
return sum;
}
void update(int x , int y ,int k , int left , int right ,int rt)
{
if(left >= x && right <= y)
{
a[rt].lazy += k;
a[rt].val += a[rt].len * k;
return;
}
if(a[rt].lazy)
pushdown(rt);
int mid = (left + right) >> 1;
if(mid >= x)
update(x , y , k , left , mid , rt << 1);
if(mid < y)
update(x , y , k , mid + 1, right , rt << 1 | 1);
a[rt].val = a[rt << 1].val + a[rt << 1 | 1].val;
}
int main()
{
scanf("%d %d" , &n , &m);
build(1 , n , 1);
char q;
int x , y , k;
while(m --)
{
cin >> q;
if(q == 'Q')
{
scanf("%d %d" , &x , &y);
printf("%lld\n" , que(x , y , 1, n , 1));
}
else
{
scanf("%d %d %d", &x , &y , &k);
update(x , y , k , 1 , n , 1);
}
}
return 0;
}