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 Output
4 55 9 15
Hint
The sums may exceed the range of 32-bit integers.
题意:Q:求L到R的和。C:L,R的数都加x
解析:关于差分:https://www.cnblogs.com/liyexin/p/11014218.html。下面c1[]和c2[]都是采用了差分的思想。
设原数组的前缀和:sum[]。数组大小为n。
设c1[i]表示i~n,每个数字+x。要[L,R]加x,那么有c1[L]+=x,c2[R+1]-=x。
对于sum[x],c1[i]对其贡献为(x-i+1)。那么求1-x的和,有:sum[1]+sum[2]+....+c1[1]*x+c1[2]*(x-1)+.....c1[x]*1。用se表示累加求和1~x,那么原式就是se(sum[x])+se(c1[i]*(x-i+1))==sum[x]+(x+1)*se(c1[i])-se(c1[i]*i)。那么se的意思也是前缀和了,所以用c1[i]为i的前缀和,c2[i]为c2[i]*i的前缀和。那么更新时,需要更新两个数组:
update(a,c,c1); update(b+1,-c,c1); update(a,a*c,c2); update(b+1,-(b+1)*c,c2);
求和时,套一下上面的公式:
ll a,b; scanf("%lld%lld",&a,&b); ll x1=sum[b]+(b+1)*get(b,c1)-get(b,c2); ll x2=sum[a-1]+a*get(a-1,c1)-get(a-1,c2); cout<<x1-x2<<endl;
#include<iostream> #include<cstdio> #include<cstring> #include<map> using namespace std; typedef long long ll; const int maxn = 1e5+10; ll sum[maxn],c1[maxn],c2[maxn]; ll n,q; ll lowbit(ll x) { return x&(-x); } void update(ll id,ll x,ll *c) { for(int i=id;i<=n;i+=lowbit(i)) { c[i]+=x; } } ll get(ll id,ll *c) { ll sum=0; for(int i=id;i>0;i=i-lowbit(i)) { sum+=c[i]; } return sum; } int main() { scanf("%lld%lld",&n,&q); ll x,ans=0; for(int i=1;i<=n;i++) { scanf("%lld",&x); ans+=x; sum[i]=ans; } while(q--) { char s[20]; scanf("%s",s); if(s[0]=='C') { ll a,b,c; scanf("%lld%lld%lld",&a,&b,&c); update(a,c,c1); update(b+1,-c,c1); update(a,a*c,c2); update(b+1,-(b+1)*c,c2); } else { ll a,b; scanf("%lld%lld",&a,&b); ll x1=sum[b]+(b+1)*get(b,c1)-get(b,c2); ll x2=sum[a-1]+a*get(a-1,c1)-get(a-1,c2); cout<<x1-x2<<endl; } } }