首页 > 编程语言 > 详细

【模板】树状数组

时间:2019-07-12 20:58:33      阅读:82      评论:0      收藏:0      [点我收藏+]

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\n",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\n",query(x));
    }
    return 0;
}
 
树状数组区间修改 单点查询

 

【模板】树状数组

原文:https://www.cnblogs.com/lxyyyy/p/11178182.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!