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;
    }
     
    树状数组区间修改 单点查询
  • 相关阅读:
    hdu4734 F(x)
    hdu2089 不要62 两解
    luogu2602 [ZJOI2010]数字计数 两解
    lemon
    UVA1218 完美的服务 Perfect Service
    luogu HNOI2003消防局的设立
    uva10891 game of sum
    uva10635 Prince and Princess
    UVA1394 And Then There Was One
    uva10003切木棍
  • 原文地址:https://www.cnblogs.com/lxyyyy/p/11178182.html
Copyright © 2011-2022 走看看