Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 130450 | Accepted: 40489 | |
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<iostream>
#include<cstdio>
#include<cstring>
#define ll long long
using namespace std;
const int maxn = 1e5+7;
int n, q;
ll s[maxn];
struct node {
int l, r;
ll sumseg, Inc;
}segTree[maxn*4];
void Build(int i, int l, int r)
{
segTree[i].l = l;
segTree[i].r = r;
segTree[i].Inc = 0;
if(l == r) {
segTree[i].sumseg = s[l];
return ;
}
int mid = (l+r)>>1;
Build(i<<1, l, mid);
Build(i<<1|1, mid+1, r);
segTree[i].sumseg = segTree[i<<1].sumseg + segTree[i<<1|1].sumseg;
//左子树和右子树;
}
void ADD(int i, int l, int r, ll c)
{
if(segTree[i].l == l&&segTree[i].r == r)
{
segTree[i].Inc += c;
return ;
}
segTree[i].sumseg += c*(r - l + 1);
int mid = (segTree[i].l + segTree[i].r)>>1;
if(r <= mid) ADD(i<<1, l, r, c);
else if(l>mid) ADD(i<<1|1, l, r, c);
else {
ADD(i<<1, l, mid, c);
ADD(i<<1|1, mid+1, r, c);
}
}
ll Query(int i, int l, int r)
{
if(segTree[i].l == l&&segTree[i].r == r) {
return segTree[i].sumseg + segTree[i].Inc*(r - l + 1);
}
segTree[i].sumseg += (segTree[i].r - segTree[i].l + 1)*segTree[i].Inc;
int mid = (segTree[i].l + segTree[i].r)>>1;
ADD(i<<1, segTree[i].l, mid, segTree[i].Inc);
ADD(i<<1|1, mid+1, segTree[i].r, segTree[i].Inc);
segTree[i].Inc = 0;
if(r <= mid) return Query(i<<1, l, r);
else if(l>mid) return Query(i<<1|1, l, r);
else return Query(i<<1, l, mid)+Query(i<<1|1, mid+1, r);
}
void checkc()
{
int a, b; ll c;
scanf("%d%d%lld",&a, &b, &c);
ADD(1, a, b, c);
}
void checkq()
{
int a, b;
scanf("%d%d",&a, &b);
printf("%lld\n", Query(1, a, b));
}
int main()
{
int i, j;
//freopen("in.txt", "r", stdin);
while(~scanf("%d%d",&n,&q))
{
for(i = 1; i <= n; i++) scanf("%lld",&s[i]);
Build(1, 1, n);
for(i = 0; i < q; i++)
{
char op; cin >> op;
if(op == 'C') checkc();
else checkq();
}
}
return 0;
}