题目
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.
题目大意
给你一个数组,要求你实现区间修改,区间查询
题解
线段树模板
代码
#include <iostream>
using namespace std;
typedef long long LL;
const int N = 1e6 + 10;
int b[N],m,n;
struct node
{
int l,r;
LL sum,tag;
}a[4*N];
void push_up(int now)
{
a[now].sum = a[now<<1].sum + a[now<<1|1].sum;
}
void build(int l, int r, int now)
{
a[now].l = l, a[now].r = r, a[now].tag = 0;
if(l == r)a[now].sum = b[l];
else
{
int mid =(l+r)>>1;
build(l,mid,now<<1);
build(mid+1,r,now<<1|1);
push_up(now);
}
}
void push_down(int x)
{
a[x<<1].tag += a[x].tag;
a[x<<1|1].tag += a[x].tag;
a[x<<1].sum += a[x].tag*(a[x<<1].r-a[x<<1].l+1);
a[x<<1|1].sum += a[x].tag*(a[x<<1|1].r-a[x<<1|1].l+1);
a[x].tag = 0;
}
void add(int l,int r, int now, LL k)
{
if(l<=a[now].l&&a[now].r<=r)
{
a[now].sum += (a[now].r-a[now].l+1)*k;
a[now].tag += k;
return;
}
if(a[now].tag)push_down(now);
if(l<=a[now<<1].r)add(l,r,now<<1,k);
if(a[now<<1|1].l<=r)add(l,r,now<<1|1,k);
push_up(now);
}
LL query(int l, int r, int now)
{
if(l<=a[now].l&&a[now].r<=r)
{
return a[now].sum;
}
if(a[now].tag)push_down(now);
LL t = 0;
if(l <= a[now<<1].r) t += query(l,r,now<<1);
if(a[now<<1|1].l <= r) t += query(l,r,now<<1|1);
return t;
}
int main()
{
char op[4];
cin >> n >> m;
for(int i = 1; i <= n; i ++)
scanf("%d",&b[i]);
build(1,n,1);
while(m--)
{
int l,r;
cin>>op>>l>>r;
if(op[0] == 'Q')
cout << query(l,r,1) << endl;
else
{
LL k;
scanf("%lld",&k);
add(l,r,1,k);
}
}
return 0;
}