树状数组 代码(洛谷为例)

又是一年板子时。
直接扔代码
C++:
树状数组1

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<ctime>
#include<queue>
#include<set>
#include<stack>
#include<map>
#include<algorithm>
#define maxn 500001
#define INF 0x3f3f3f3f
#define inf 0x3f
#define maxm 1001
using namespace std;
int a[maxn],c[maxn],n,m,d,e;
int lb(int x){
    return x&(-x);
}
int sum(int x){
    int ret=0;
    while(x>0){
        ret+=c[x];
        x-=lb(x);
    }
    return ret;
}
void add(int x,int d){
    while(x<=n){
        c[x]+=d;
        x+=lb(x);
    }
}
int qwq;
int main(){
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        cin>>a[i];
        add(i,a[i]);
    }
    for(int i=1;i<=m;i++){
        cin>>qwq>>d>>e;
        if(qwq==1) {
            add(d,e);
        }
        if(qwq==2) {
            cout<<sum(e)-sum(d-1)<<endl;
        }
    }
    return 0;
}

树状数组2

// luogu-judger-enable-o2
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<ctime>
#include<queue>
#include<set>
#include<stack>
#include<map>
#include<algorithm>
#define maxn 500001
#define INF 0x3f3f3f3f
#define inf 0x3f
#define maxm 1001
using namespace std;
int a[maxn],c[maxn],n,m,d,e;
int lb(int x){
    return x&(-x);
}
int sum(int x){
    int ret=0;
    while(x>0){
        ret+=c[x];
        x-=lb(x);
    }
    return ret;
}
void add(int x,int d){
    while(x<=n){
        c[x]+=d;
        x+=lb(x);
    }
}
int query(int x){
    int ans=0;
    while(x>0){
        ans+=c[x];
        x-=lb(x);
    }
    return ans;
}
int qwq;
int main(){
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        cin>>a[i];
        add(i,a[i]-a[i-1]);
    }
    for(int i=1;i<=m;i++){
        cin>>qwq;
        if(qwq==1){
            int k;
            cin>>d>>e>>k;
            add(d,k);
            add(e+1,-k);
        }
        if(qwq==2){
            cin>>d;
            cout<<query(d)<<endl;
        }
    }
    return 0;
}

 

posted @ 2018-08-18 09:37  kenlig  阅读(584)  评论(0编辑  收藏  举报