Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 107448 | Accepted: 33516 | |
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
POJ Monthly--2007.11.25, Yang Yi
线段树区间更新裸题
#include <stdio.h>
#include <string.h>
using namespace std;
const int N = 100000 + 10;
long long n, m;
struct xx{
long long l, r, v, add;
}T[N*4];
void Pushup(long long k){
T[k].v = T[k<<1].v + T[k<<1|1].v;
}
void Pushdown(long long k){
T[k<<1].add += T[k].add;
T[k<<1|1].add += T[k].add;
T[k<<1].v += T[k].add*(T[k<<1].r-T[k<<1].l+1);
T[k<<1|1].v += T[k].add*(T[k<<1|1].r-T[k<<1|1].l+1);
T[k].add = 0;
}
void Build(long long l, long long r, long long k){
T[k].l = l, T[k].r = r, T[k].add = 0;
if(l == r){
scanf("%lld", &T[k].v);
return;
}
long long mid = (l+r)>>1;
Build(l, mid, k<<1);
Build(mid+1, r, k<<1|1);
Pushup(k);
}
void Update(long long l, long long r, long long c, long long k){
if(l > T[k].r || r < T[k].l){
return;
}
if(l <= T[k].l && r >= T[k].r){
T[k].add += c;
T[k].v += c*(T[k].r-T[k].l+1);
return;
}
if(T[k].add) Pushdown(k);
Update(l, r, c, k<<1);
Update(l, r, c, k<<1|1);
Pushup(k);
}
long long ans;
void Query(long long l, long long r, long long k){
if(l > T[k].r || r < T[k].l){
return;
}
if(l <= T[k].l && r >= T[k].r){
ans += T[k].v;
return;
}
if(T[k].add) Pushdown(k);
long long mid = (T[k].l+T[k].r)>>1;
if(r <= mid) Query(l, r, k<<1);
else if(l > mid) Query(l, r, k<<1|1);
else{
Query(l, mid, k<<1);
Query(mid+1, r, k<<1|1);
}
}
int main(){
while(scanf("%lld%lld", &n, &m) == 2){
Build(1, n, 1);
while(m--){
char op[5];
long long u, v, w;
scanf("%s", op);
if(op[0] == 'Q'){
scanf("%lld%lld", &u, &v);
ans = 0;
Query(u, v, 1);
printf("%lld\n", ans);
}
else{
scanf("%lld%lld%lld", &u, &v, &w);
Update(u, v, w, 1);
}
}
}
}