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.
线段树模板题,区间更新时候那个延迟标记要注意,求区间和,每次val值要加上区间长度乘以addval值,求区间最大值,每次val值直接加上addval值即可
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<map>
#include<queue>
using namespace std;
typedef long long LL;
const int inf = 0x3f3f3f3f;
#define pb push_back
#define mp make_pair
#define fi first
#define se second
const int N = 2 * 1e5 + 5;
typedef struct Node{
LL val,addval;
}Node;
Node tree[N << 2];
LL a[N];
void build(int root,int l,int r)
{
tree[root].addval = 0;
if(l == r){
tree[root].val = a[l];
return ;
}
int mid = (l + r) / 2;
build(root * 2 + 1,l,mid);
build(root * 2 + 2,mid + 1,r);
tree[root].val = tree[root * 2 + 1].val + tree[root * 2 + 2].val;
}
void pushdown(int root,int m)
{
if(tree[root].addval != 0){
tree[root * 2 + 1].addval += tree[root].addval;
tree[root * 2 + 2].addval += tree[root].addval;
tree[root * 2 + 1].val += (m - (m >> 1)) * tree[root].addval;
tree[root * 2 + 2].val += (m >> 1) * tree[root].addval;
tree[root].addval = 0;
}
}
void update(int root,int l,int r,int pl,int pr,int val)
{
if(r < pl || l > pr){
return ;
}
if(l >= pl && r <= pr){
tree[root].addval += val;
tree[root].val += (r - l + 1) * val;
return ;
}
pushdown(root,r - l + 1);
int mid = (l + r) / 2;
if(pl <= mid){
update(root * 2 + 1,l,mid,pl,pr,val);
}
if(pr > mid){
update(root * 2 + 2,mid + 1,r,pl,pr,val);
}
tree[root].val = tree[root * 2 + 1].val + tree[root * 2 + 2].val;
}
LL query(int root,int l,int r,int pl,int pr)
{
if(r < pl || l > pr){
return 0;
}
if(l >= pl && r <= pr){
return tree[root].val;
}
pushdown(root,r - l + 1);
int mid = (l + r) / 2;
LL sum = 0;
if(pl <= mid){
sum += query(root * 2 + 1,l,mid,pl,pr);
}
if(pr > mid){
sum += query(root * 2 + 2,mid + 1,r,pl,pr);
}
return sum;
}
int main()
{
int n,q;
while(~scanf("%d %d",&n,&q))
{
for(int i = 1;i <= n;++i){
scanf("%lld",&a[i]);
}
build(1,1,n);
for(int i = 0;i < q;++i){
char s[5];
scanf("%s",s);
if(s[0] == 'Q'){
int x,y;
scanf("%d %d",&x,&y);
printf("%lld\n",query(1,1,n,x,y));
}else{
int x,y,z;
scanf("%d %d %d",&x,&y,&z);
update(1,1,n,x,y,z);
}
}
}
return 0;
}