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
The sums may exceed the range of 32-bit integers.
题意
N个数,Q个操作,访问区间和,修改区间的值,给区间每一个数增大某个值
思路
线段树lazy标记,增加的是区间内每一个数,lazy需要写成+= 。
lazy和w需要用long long,乘法的地方需要1ll* ,int会爆。
#include <iostream>
#include <cstdio>
#define ll long long
using namespace std;
struct node
{
int l,r;
ll w,lazy;
};
node tree[100010*4];
ll init[100010*4];
void build(int k,int l,int r)
{
tree[k].l = l; tree[k].r = r; tree[k].lazy = 0;
if(l==r){
tree[k].w = init[l];
return;
}
int mid = (l + r)/2;
build(k*2,l,mid);
build(k*2+1,mid+1,r);
tree[k].w = tree[k*2].w + tree[k*2+1].w;
}
void pushdown(int k)
{
tree[k*2].lazy += tree[k].lazy;
tree[k*2+1].lazy += tree[k].lazy;
int len = tree[k].r - tree[k].l + 1;
tree[k*2].w += (len-len/2)*tree[k].lazy;
tree[k*2+1].w += (len/2)*tree[k].lazy;
tree[k].lazy = 0;
}
void update(int k,int l,int r,int v)// 区间修改,l-r区间修改为增加v
{
if(l>tree[k].r||r<tree[k].l) return;
if(l<=tree[k].l&&tree[k].r<=r){
tree[k].lazy += v; //加标记
tree[k].w += (tree[k].r - tree[k].l + 1)*v;
return;
}
if(tree[k].lazy) pushdown(k);
update(k*2,l,r,v);
update(k*2+1,l,r,v);
tree[k].w = tree[k*2].w + tree[k*2+1].w;
}
ll query(int k,int l,int r)
{
if(l>tree[k].r||r<tree[k].l) return 0;
if(tree[k].lazy) pushdown(k);
if(l<=tree[k].l&&tree[k].r<=r) return tree[k].w;
return query(k*2,l,r) + query(k*2+1,l,r);
}
int main()
{
int N,T,a,b;
int c;
scanf("%d%d",&N,&T);
for(int i=1;i<=N;i++){
scanf("%lld",&init[i]);
}
build(1,1,N);
for(int i=1;i<=T;i++){
char ch; scanf(" %c",&ch);
if(ch=='Q'){
scanf("%d%d",&a,&b);
printf("%lld\n",query(1,a,b));
}
else if(ch=='C'){
scanf("%d%d%d",&a,&b,&c);
update(1,a,b,c);
}
}
}