zoukankan      html  css  js  c++  java
  • 【模板】树状数组

    P3374 【模板】树状数组 1     P3368 【模板】树状数组 2 

    是看了逆序对之后决定把这个复习一下 因为哪里都在说线段树比它好多了emmmm

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<cmath>
    #include<algorithm>
    using namespace std;
    #define ll long long
    #define rg register
    const int N=500000+5,M=200000+5,inf=0x3f3f3f3f,P=19650827;
    int n,m;
    ll tree[N<<1];
    template <class t>void rd(t &x){
        x=0;int w=0;char ch=0;
        while(!isdigit(ch)) w|=ch=='-',ch=getchar();
        while(isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
        x=w?-x:x;
    }
    
    #define Max(x,y) (x)>(y)?(x):(y)
    #define Min(x,y) (x)>(y)?(y):(x)
    int lowbit(int x){return x&(-x);}
    
    void update(int pos,ll add){
        while(pos<=n) tree[pos]+=add,pos+=lowbit(pos);
    }
    
    ll query(ll pos){
        ll ans=0;
        while(pos>0) ans+=tree[pos],pos-=lowbit(pos);
        return ans;
    }
    
    int main(){
    //    freopen("in.txt","r",stdin);
        rd(n),rd(m);
        for(ll i=1,x;i<=n;++i) rd(x),update(i,x);
        while(m--){
            int op,x,y;
            rd(op),rd(x),rd(y);
            if(op==1) update(x,y);
            else printf("%lld
    ",query(y)-query(x-1));
        }
        return 0;
    }
     
    树状数组单点修改 区间查询
    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<cmath>
    #include<algorithm>
    using namespace std;
    #define ll long long
    #define rg register
    const int N=500000+5,M=200000+5,inf=0x3f3f3f3f,P=19650827;
    int n,m;
    ll tree[N<<1],a[N<<1];
    template <class t>void rd(t &x){
        x=0;int w=0;char ch=0;
        while(!isdigit(ch)) w|=ch=='-',ch=getchar();
        while(isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
        x=w?-x:x;
    }
    
    #define Max(x,y) (x)>(y)?(x):(y)
    #define Min(x,y) (x)>(y)?(y):(x)
    int lowbit(int x){return x&(-x);}
    
    void update(int pos,ll ad){
        while(pos<=n) tree[pos]+=ad,pos+=lowbit(pos);
    }
    
    ll query(ll pos){
        ll ans=0;
        while(pos>0) ans+=tree[pos],pos-=lowbit(pos);
        return ans;
    }
    
    int main(){
    //    freopen("in.txt","r",stdin);
        rd(n),rd(m);
        for(ll i=1,x;i<=n;++i) rd(a[i]),update(i,a[i]-a[i-1]);
        while(m--){
            int op,x,y,k;
            rd(op),rd(x);
            if(op==1) rd(y),rd(k),update(x,k),update(y+1,-k);
            else printf("%lld
    ",query(x));
        }
        return 0;
    }
     
    树状数组区间修改 单点查询
  • 相关阅读:
    【NOIP 2003】 加分二叉树
    【POJ 1655】 Balancing Act
    【HDU 3613】Best Reward
    【POJ 3461】 Oulipo
    【POJ 2752】 Seek the Name, Seek the Fame
    【POJ 1961】 Period
    【POJ 2406】 Power Strings
    BZOJ3028 食物(生成函数)
    BZOJ5372 PKUSC2018神仙的游戏(NTT)
    BZOJ4836 二元运算(分治FFT)
  • 原文地址:https://www.cnblogs.com/lxyyyy/p/11178182.html
Copyright © 2011-2022 走看看