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 Outpu
t
4 55 9 15
Hint
The sums may exceed the range of 32-bit integers.
这次用的是分块的思想,比线段树好理解,比树状数组更好理解,但是复杂度高了。
AC代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<stdlib.h>
#include<queue>
#include<map>
#include<iomanip>
#include<math.h>
using namespace std;
typedef long long ll;
typedef double ld;
const int INF = 0x3f3f3f3f;
const int N=1000010;
ll a[N],sum[N],add[N];
int L[N],R[N]; //每一段的左右端点
int pos[N]; //每个位置属于哪一段
int n,m,t;
void change(int l,int r,ll d)
{
int p = pos[l];
int q = pos[r];
if(p==q)
{
for(int i=l; i<=r; i++)
a[i]+=d;
sum[p] += d*(r-l+1);
}
else
{
for(int i=p+1; i<=q-1; i++)
add[i]+=d;
for(int i=l; i<=R[p]; i++)
a[i]+=d;
sum[p]+=d*(R[p]-l+1);
for(int i=L[q]; i<=r; i++)
a[i]+=d;
sum[q]+=d*(r-L[q]+1);
}
}
ll ask(int l,int r)
{
int p = pos[l];
int q = pos[r];
ll ans=0;
if(p==q)
{
for(int i=l; i<=r; i++)
ans+=a[i];
ans+=add[p]*(r-l+1);
}
else
{
for(int i=p+1; i<=q-1; i++)
ans+=sum[i]+add[i]*(R[i]-L[i]+1);
for(int i=l; i<=R[p]; i++)
ans+=a[i];
ans+=add[p]*(R[p]-l+1);
for(int i=L[q]; i<=r; i++)
ans+=a[i];
ans += add[q]*(r-L[q]+1);
}
return ans;
}
int main()
{
scanf("%d %d",&n,&m);
for(int i=1; i<=n; i++)
scanf("%lld",&a[i]);
//分块
t=sqrt(n);
for(int i=1; i<=t; i++)
{
L[i]=(i-1)*sqrt(n)+1;
R[i]=i*sqrt(n);
}
if(R[t]<n)
{
t++;
L[t]=R[t-1]+1;
R[t]=n;
}
//预处理
for(int i=1; i<=t; i++)
{
for(int j=L[i]; j<=R[i]; j++)
{
pos[j]=i;
sum[i]+=a[j];
}
}
while(m--)
{
char op[3];
int l,r,d;
scanf("%s %d %d",op,&l,&r);
if(op[0]=='C')
{
scanf("%d",&d);
change(l,r,d);
}
else
printf("%lld\n",ask(l,r));
}
return 0;
}