Time Limit: 5000MS | | Memory Limit: 131072K |
Total Submissions: 22796 | | Accepted: 6106 |
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>
#include <algorithm>
#define lch rt*2,l,m
#define rch rt*2+1,m+1,r
using namespace std;
typedef long long ll;
const int maxn = 1e6 + 5;
ll tree[maxn*4], mark[maxn*4];
void pushup(int rt)
{
tree[rt] = tree[rt*2+1] + tree[rt*2]; //这里是等于
}
void pushdown(int rt, int l, int r)
{
int m = (l+r)/2;
mark[rt*2] += mark[rt]; //这里都是+=
tree[rt*2] += mark[rt]*(m-l+1);
mark[rt*2+1] += mark[rt];
tree[rt*2+1] += mark[rt]*(r-m);
mark[rt] = 0; //不要忘记最后给mark变成0
}
void build(int rt, int l, int r)
{
if(l == r)
{
scanf("%lld", &tree[rt]);
return;
}
int m = (l+r)/2;
build(lch);
build(rch);
pushup(rt); //更新
}
void update(int rt, int l, int r, int i, int j, int val)
{
if(l >= i && r <= j) //一定要去见覆盖
{
tree[rt] += (r-l+1)*val; //这里是 +=
mark[rt] += val;
return;
}
if(mark[rt]) pushdown(rt,l,r);
int m = (l+r)/2;
if(i <= m) update(lch,i,j, val);
if(j > m) update(rch,i,j, val);
pushup(rt); //这里要更新
}
ll query(int rt, int l, int r, int i, int j)
{
if(l >= i && r <= j) //区间覆盖
{
return tree[rt];
}
if(mark[rt]) pushdown(rt,l,r);
int m = (l+r)/2;
ll ans = 0;
if(i <= m) ans += query(lch,i,j);
if(j > m) ans += query(rch,i,j);
return ans;
}
int main()
{
int n, m;
while(~scanf("%d%d", &n, &m))
{
memset(mark, 0, sizeof(mark));
build(1,1,n);
char cmd;
int i, j, val;
while(m--)
{
scanf(" %c", &cmd);
if(cmd == 'Q')
{
scanf("%d%d", &i, &j);
printf("%lld\n", query(1,1,n,i,j));
}
else
{
scanf("%d%d%d", &i, &j, &val);
update(1, 1, n, i, j, val);
}
}
}
return 0;
}