洛谷模板,树状数组1

题目链接:https://www.luogu.org/problemnew/show/P3374

我的理解就是树状数组其实就是线段树的阉割版,线段树能干的树状数组不一定能,但树状数组能干的线段树都能干

当然好处是树状数组的效率要比线段树快一丢丢,并且实现起来简单不少

树状数组入门:https://blog.csdn.net/Small_Orange_glory/article/details/81290634

就是用二进制做的,代码记记吧

#include <bits/stdc++.h>
using namespace std;
const double pi=acos(-1);
const int mod=10007;
const int maxn=2e6+7;//注意这里也要开四倍大小 
typedef long long ll;
int n,m,tree[maxn];
int lowbit(int t){
    return t&-t;
}
void add(int x,int k){
    while(x<=n){
        tree[x]+=k;
        x+=lowbit(x);
    }
}
int sum(int x){
    int ans=0;
    while(x!=0){
        ans+=tree[x];
        x-=lowbit(x);
    }
    return ans;
}
int main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++){
        int a;scanf("%d",&a);//注意这里的输入必须得用add函数来实现
        add(i,a); 
    } 
    int type,x,y;
    while(m--){
        scanf("%d%d%d",&type,&x,&y);
            if(type==1){
                add(x,y);
            }
            if(type==2){
                cout<<sum(y)-sum(x-1)<<endl;
            }
        }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/qingjiuling/p/10532940.html
今日推荐