A Simple Problem with Integers
You have N N N integers, A 1 , A 2 , . . . , A N A_1, A_2, ... , A_N 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
N
N and
Q
Q
Q.
1
≤
N
,
Q
≤
100000
1 ≤ N,Q ≤ 100000
1≤N,Q≤100000.
The second line contains
N
N
N numbers, the initial values of
A
1
,
A
2
,
.
.
.
,
A
N
A_1, A_2, ... , A_N
A1,A2,...,AN.
−
1000000000
≤
A
i
≤
1000000000.
-1000000000 ≤ A_i ≤ 1000000000.
−1000000000≤Ai≤1000000000.
Each of the next Q lines represents an operation.
“C a b c” means adding c to each of
A
a
,
A
a
+
1
,
.
.
.
,
A
b
A_a, A_{a+1}, ... , A_b
Aa,Aa+1,...,Ab.
−
10000
≤
c
≤
10000.
-10000 ≤ c ≤ 10000.
−10000≤c≤10000.
“Q a b” means querying the sum of
A
a
,
A
a
+
1
,
.
.
.
,
A
b
A_a, A_{a+1}, ... , A_b
Aa,Aa+1,...,Ab.
Output
You need to answer all Q Q 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
思路
用分块算法,把n分为若干个区间,用"大段维护,局部朴素"的方法来维护全局。
#include<cstdio>
#include<cmath>
#define int long long
using namespace std;
const int maxn=1e5+10;
int sum[maxn],add[maxn],n,m,t,l,r,v;
int a[maxn],L[maxn],R[maxn],pos[maxn];
char op[3];
int ask(int l,int r){
int p=pos[l],q=pos[r],ret=0;
if(p==q){
for(int i=l;i<=r;i++) ret+=a[i];
ret+=add[p]*(r-l+1);
}else{
ret+=ask(l,R[p]),ret+=ask(L[q],r);
for(int i=p+1;i<q;i++) ret+=sum[i]+add[i]*(R[i]-L[i]+1);
}
return ret;
}
void change(int l,int r,int v){
int p=pos[l],q=pos[r];
if(p==q){
for(int i=l;i<=r;i++) a[i]+=v;
sum[p]+=v*(r-l+1);
}else{
change(l,R[p],v),change(L[q],r,v);
for(int i=p+1;i<q;i++) add[i]+=v;
}
}
signed main(){
scanf("%lld%lld",&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)*t+1;
R[i]=i*t;
}
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--){
scanf("%s%lld%lld",op,&l,&r);
if(op[0]=='Q') printf("%lld\n",ask(l,r));
else{
scanf("%lld",&v);
change(l,r,v);
}
}
}