树状数组 求调

P3372 【模板】线段树 1

wu_18 @ 2024-12-17 19:32:11

#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,m,a[100005],t[100005];
void in(){
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        cin>>a[i];
    }
}
int lowbit(int x){
    return x&-x;
}
void add(int x,int k){
    while(x<=n){
        t[x]=t[x]+k;
        x=x+lowbit(x);
    }
}
void init(){
    for(int i=1;i<=n;++i){
        t[i]+=a[i];
        int j=i+lowbit(i);
        if(j<=n) t[j]+=t[i];
    }
}
int getsum(int x){
    int ans=0;
    while(x>0){
        ans=ans+t[x];
        x=x-lowbit(x);
    }
    return ans;
}
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    in();
    init();
    for(int i=1;i<=m;i++){
        char c;
        int l,r,d;
        cin>>c;
        if(c=='1'){
            cin>>l>>r>>d;
            for(int i=l;i<=r;i++) add(i,d);
        }
        if(c=='2'){
            int sum=0;
            cin>>l>>r;
            for(int i=l;i<=r;i++){
                sum+=getsum(i);
            }
            cout<<getsum(r)-getsum(l-1)<<'\n';
        }
    }
    return 0;
}

by SUPER_ZJC @ 2024-12-17 19:35:49

你的复杂度比暴力还劣


by littlep001 @ 2024-12-17 19:39:05

你的复杂度O(n^{2}log_2n),比暴力还差


by A_R_O_N_A @ 2024-12-17 21:20:04

@wu_18 哥们你要么就打线段树,要么就去仔细研究研究区间加区间和树状数组到底怎么写


|