zoukankan      html  css  js  c++  java
  • 洛谷模板,树状数组1

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

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

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

    具体来说树状数组最坏情况时间复杂度为nlongn ,而线段树平均为nlongn,且树状数组空间复杂度为maxn,而线段树为4*maxn(有优化为2*maxn的方法)

    树状数组入门: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){//用来取出t的最低位1
        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;
    }
  • 相关阅读:
    py笔记之循环结构
    PY学习记录#5
    PY学习记录#4
    py笔记之选择结构
    PY学习记录#3
    分享一个可以随时随地写代码的工具
    PY学习记录#2
    日记啊
    Tarjan学习笔记
    Docker commands
  • 原文地址:https://www.cnblogs.com/qingjiuling/p/10532940.html
Copyright © 2011-2022 走看看