树状数组 区间修改查询

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

#define N 200010
typedef long long ll;

int n,m;
ll sum[N],A[N],B[N];  //原始前缀和,

inline int read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch<='9'&&ch>='0'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}

inline int lowbit(int x)
{
    return x&(-x);
}

void Add(ll *q,int x,ll val)
{
    for(int i=x;i<=n;i+=lowbit(i))
        q[i]+=val;
}

ll Query(ll *q,int x)
{
    ll sum=0;
    for(int i=x;i>0;i-=lowbit(i))
        sum+=q[i];
    return sum;
}

ll Sum(int x,int y)
{
    ll t1=sum[x-1]+Query(A,x-1)*x-Query(B,x-1);
    ll t2=sum[y]+Query(A,y)*(y+1)-Query(B,y);
    return t2-t1;
}

int main()
{
    n=read();
    for(int i=1;i<=n;i++)
    {
        int x=read();
        sum[i]=sum[i-1]+x;
    }
    m=read();
    for(int i=1;i<=m;i++)
    {
        int kind=read();
        if(kind==1)
        {
            int x=read(),y=read(),z=read();
            Add(A,x,z);Add(A,y+1,z*(-1));
            Add(B,x,(long long)x*z);Add(B,y+1,(long long)z*(y+1)*(-1));
        }
        else
        {
            int x=read(),y=read();
            printf("%lld\n",Sum(x,y));
        }
    }
    return 0;
}


你可能感兴趣的:(树状数组)