zoukankan      html  css  js  c++  java
  • 树状数组

    单点修改,区间查询:

    int n,m;
    int E[maxn];
    void add(int x,int v){
        while(x<=n){
            E[x]+=v;
            x+=lowbit(x);
        }
    }
    int query(int x){
        int ans=0;
        while(x>0){
            ans+=E[x];
            x-=lowbit(x);
        }
        return ans;
    }
    int main(){
        fio;
        cin>>n>>m;
        memset(E,0,sizeof(E));
        int x;
        for(int i=1;i<=n;i++){
            cin>>x;
            add(i,x);
        }
        int op,y;
        while(m--){
            cin>>op>>x>>y;
            if(op==1){
                add(x,y);
            }
            else if(op==2){
                cout<<query(y)-query(x-1)<<endl;
            }
        }
    }

    区间修改,单点查询:

    LL c[maxn],a[maxn];
    int n,m;
    void update(int x,int y,LL add){
        while(x<=n){
            c[x]+=add;
            x+=lowbit(x);
        }
        while(y<=n){
            c[y]-=add;
            y+=lowbit(y);
        }
    }
    void update(int x,LL add){
        while(x<=n){
            c[x]+=add;
            x+=lowbit(x);
        }
    }
    LL query(int x){
        LL ans=0;
        while(x>0){
            ans+=c[x];
            x-=lowbit(x);
        }
        return ans;
    }
    int main(){
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n;i++){
            scanf("%lld",&a[i]);
            update(i,a[i]-a[i-1]);
        }
        int opt,x,y;
        LL z;
        for(int i=0;i<m;i++){
            scanf("%d",&opt);
            if(opt==1){
                scanf("%d%d%lld",&x,&y,&z);
                update(x,y+1,z);
            }
            else if(opt==2){
                scanf("%d",&x);
                printf("%lld
    ",query(x));
            }
        }
    
    }

     区间修改,区间查询

    LL c1[maxn],c2[maxn],a[maxn];
    int n,m;
    void add(int x,int y){
        while(x<=n) {
            c1[i]+=y,c2[i]+=(long long)x*y;
            x+=lowbit(x);
        }
    }
    int query(int x){
        int ans=0;
        for(x>=0){
            ans+=(x+1)*c1[i]-c2[i];
            x-=lowbit(x);
        }
        return ans;
    }
  • 相关阅读:
    [C++] static member variable and static const member variable
    [C++] const inside class VS const outside class
    [C++] OOP
    [C++] Function Template
    [C++] right value reference
    [C++] advanced reference
    [C++] const and char*
    [C++] c Struct VS c++ Struct
    [C++] decltype(auto) C++ 11 feature
    easyui-validatebox 的简单长度验证
  • 原文地址:https://www.cnblogs.com/Profish/p/9737679.html
Copyright © 2011-2022 走看看