树状数组区间更改差分数组原理

树状数组总结

 

1、单点更新,区间求和

int c[MAXN];
int sum(int x)
{
    int res=0;
    while(x)
    {
        res+=c[x];
        x-=lowbit(x);
        return res;
    }
void add(int x,int n)
{
    while(x<MAXN)
    {
        arr[x]+=n;
        x+=lowbit(x);
    }
int query(int x,int y)
{
    return sum(y)-sum(x-1);
}

2、区间更新,单点查找

int c[MAXN];//差分数组对应的树状数组
int sum(int x)
{
    int res=0;
    while(x)
    {
        res+=c[x];
        x-=lowbit(x);
        return res;
    }
void add(int x,int n)
{
    while(x<MAXN)
    {
        c[x]+=n;
        x+=lowbit(x);
    }
}
int update(int x,int y,int n)
{
    add(x,n);
    add(y+1,-n);
}

3、区间更新,区间查询

#include<bits/stdc++.h>
using namespace std;

void add(int *c,int i,int date)
{
    while(i<=n)
    {
        c[i]+=date;
        i+=lowbit(i);
    }
}

int getsum(int *c,int i)
{
    ans=0;
    while(i>0)
    {
        ans+=c[i];
        i-=lowbit(i);
    }
    return ans;
}

int main()
{
    for(i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
        add(c1,i,a[i]-a[i-1]);
        add(c2,i,(i-1)*(a[i]-a[i-1]));
    }
    //a数组[x,y]区间求和
    sum1=(x-1)*getsum(c1,x-1)-getsum(c2,x-1);
    sum2=y*getsum(c1,y)-getsum(c2,y);
    ans=sum2-sum1;
    //x~y区间同时加z
    add(c1,x,z);
    add(c1,y+1,-z);
    add(c2,x,z*(x-1));
    add(c2,y+1,-z*y);
    return 0;
}

 

相关文章:

  • 2022-12-23
  • 2021-09-01
  • 2021-09-08
  • 2021-07-28
  • 2021-11-10
  • 2021-08-04
  • 2021-09-15
  • 2022-12-23
猜你喜欢
  • 2021-11-18
  • 2022-02-23
  • 2022-12-23
相关资源
相似解决方案