A Simple Problem with Integers(树状数组区间变化和区间求和)

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<cstring>
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
#define maxn 100004
ll a[maxn],c1[maxn],c2[maxn];
ll n,m;
ll lowbit(ll x){
    return x&(-x);
}
void updata(ll index,ll x,ll val)
{
    if(index==0) 
        for(int i=x;i<=n;i+=lowbit(i)) 
            c1[i]+=val;//建立树状数 
    else 
        for(int i=x;i<=n;i+=lowbit(i)) 
            c2[i]+=(x-1)*val;//区间改变 
}

ll getsum(ll x)
{
    ll sum1=0,sum2=0;
    for(int i=x;i>0;i-=lowbit(i))//无论变不变化都可用来求和  
    sum1+=c1[i],sum2+=c2[i];//区间求和//(l,r)的和为getsum(r)-getsum(l-1) 
    return x*sum1-sum2;
}

int main()
{
    a[0]=0;
    scanf("%lld%lld",&n,&m);
    for(int i = 1; i <= n; i++){
            scanf("%lld",&a[i]);
            ll t=a[i]-a[i-1];
            updata(0,i,t);
            updata(1,i,t);   //输入初值的时候,也相当于更新了值
    }
    char v;
    ll ans1,ans2;
    ll l,r,add;
    for(int i=1;i<=m;i++){
        getchar();
        scanf("%c",&v);        
        if(v=='C'){
            scanf("%lld%lld%lld",&l,&r,&add);
            updata(0,l,add);
            updata(0,r+1,-add);
            updata(1,l,add);
            updata(1,r+1,-add); 
        }
        else{
            scanf("%lld%lld",&l,&r);
            ans1=getsum(r);
            ans2=getsum(l-1);
            printf("%lld\n",ans1-ans2);
        }
    }
    return 0;
}

 

 
 

猜你喜欢

转载自www.cnblogs.com/lipu123/p/12194480.html