A Simple Problem with Integers
https://vjudge.net/problem/POJ-3468
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.
C++
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 100000 + 10;
typedef long long LL;
LL num[MAXN];
struct node{
int l, r;
LL lazy, sum;
}segTree[MAXN << 2];
void pushup(int x)
{
segTree[x].sum = segTree[x << 1].sum + segTree[x << 1 | 1].sum;
}
void pushdown(int x)
{
if(segTree[x].lazy)
{
segTree[x << 1].lazy += segTree[x].lazy;
segTree[x << 1 | 1].lazy += segTree[x].lazy;
segTree[x << 1].sum += (segTree[x << 1].r - segTree[x << 1].l + 1) * segTree[x].lazy;
segTree[x << 1 | 1].sum += (segTree[x << 1 | 1].r - segTree[x << 1 | 1].l + 1) * segTree[x].lazy;
segTree[x].lazy = 0;
}
}
void build(int x, int l, int r)
{
segTree[x].l = l;
segTree[x].r = r;
segTree[x].lazy = 0;
if(l == r)
{
segTree[x].sum = num[l];
return;
}
int mid = l + r >> 1;
build(x << 1, l, mid);
build(x << 1 | 1, mid + 1, r);
pushup(x);
}
void update(int x, int l, int r, LL val)
{
if(l <= segTree[x].l && segTree[x].r <= r)
{
segTree[x].sum += (segTree[x].r - segTree[x].l + 1) * val;
segTree[x].lazy += val;
return;
}
pushdown(x);
int mid = segTree[x].l + segTree[x].r >> 1;
if(r <= mid) update(x << 1, l, r, val);
else if(l > mid) update(x << 1 | 1, l, r, val);
else
{
update(x << 1, l, mid, val);
update(x << 1 | 1, mid + 1, r, val);
}
pushup(x);
}
LL query(int x, int l, int r)
{
if(l <= segTree[x].l && segTree[x].r <= r)
return segTree[x].sum;
pushdown(x);
int mid = segTree[x].l + segTree[x].r >> 1;
if(r <= mid) return query(x << 1, l, r);
else if(l > mid) return query(x << 1 | 1, l, r);
else return query(x << 1, l, mid) + query(x << 1 | 1, mid + 1, r);
}
int main()
{
int n, m;
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i ++)
scanf("%lld", &num[i]);
build(1, 1, n);
char op;
int a, b;
LL c;
for(int i = 0; i < m; i ++)
{
getchar();
scanf("%c", &op);
if(op == 'Q')
{
scanf("%d%d", &a, &b);
printf("%lld\n", query(1, a, b));
}
else
{
scanf("%d%d%lld", &a, &b, &c);
update(1, a, b, c);
}
}
return 0;
}