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 <cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn = 1e6+100;
struct node
{
ll sum,lazy;
}tree[maxn<<2];
int n, num[maxn];
void pushup(long long root)
{
tree[root].sum = tree[root<<1].sum + tree[root<<1|1].sum;
}
void pushdown(ll root,ll l,ll r)
{
if(tree[root].lazy == 0)
return ;
int chl = root<<1;
int chr = root<<1|1;
int mid = l + r>>1;
tree[chl].sum += tree[root].lazy * (mid-l+1);
tree[chr].sum += tree[root].lazy * (r-mid);
tree[chl].lazy += tree[root].lazy;
tree[chr].lazy += tree[root].lazy;
tree[root].lazy = 0;
}
void buildtree(ll l,ll r,ll root)
{
tree[root].lazy = 0;
if(l == r)
{
tree[root].sum=num[l];
return ;
}
ll mid = (l + r) >> 1;
buildtree(l,mid,root<<1);
buildtree(mid+1,r,root<<1|1);
pushup(root);
}
ll query(ll ql,ll qr,ll l,ll r,ll root)
{
if(l == ql && qr ==r)
{
return tree[root].sum;
}
ll mid = (l + r)>>1;
pushdown(root,l,r);
if(qr <= mid)
{
return query(ql,qr,l,mid,root<<1);
}
else if(ql > mid)
{
return query(ql,qr,mid+1,r,root<<1|1);
}
else
return query(mid+1,qr,mid+1,r,root<<1|1)+ query(ql,mid,l,mid,root<<1);
}
void change(ll ql,ll qr,ll l,ll r,ll root,ll h)
{
if(l == ql && qr==r)
{
tree[root].lazy += h;
tree[root].sum += (r - l +1)*h;
return;
}
pushdown(root,l,r);
ll mid = (l + r) >> 1;
if(qr <= mid)
change(ql,qr,l,mid,root<<1,h);
else if(ql > mid)
change(ql,qr,mid+1,r,root<<1|1,h);
else
{
change(ql,mid,l,mid,root<<1,h);
change(mid+1,qr,mid+1,r,root<<1|1,h);
}
pushup(root);
}
int main()
{
ll n,m;
while(scanf("%lld%lld",&n,&m)!= EOF)
{
ll sum = 0;
for(int i=1;i<=n;i++)
scanf("%d",&num[i]);
buildtree(1,n,1);
while(m--)
{
ll a,b,h;
char c[10];
scanf("%s",&c);
if(c[0] == 'C')
{
scanf("%lld%lld%lld",&a,&b,&h);
change(a,b,1,n,1,h);
}
else if(c[0] == 'Q')
{
scanf("%lld%lld",&a,&b);
sum = query(a,b,1,n,1);
printf("%lld\n",sum);
}
}
}
return 0;
}