刚学树状数组70WA求助

P3372 【模板】线段树 1

cqbzhr @ 2024-01-04 17:14:24

#include <bits/stdc++.h>
using namespace std;
long long n,m,a[100005],tree1[100005],tree2[100005],x,y,k,t;
int lowbit(int x){
    return x&(-x);
}
void update1(long long x,long long d){
    while(x<=n){
        tree1[x]+=d;
        x+=lowbit(x);
    }
}
void update2(long long x,long long d){
    while(x<=n){
        tree2[x]+=d;
        x+=lowbit(x);
    }
}
long long prefix1(long long x){
    long long ans=0;
    while(x>0){
        ans+=tree1[x];
        x-=lowbit(x);
    }
    return ans;
}
long long prefix2(long long x){
    long long ans=0;
    while(x>0){
        ans+=tree2[x];
        x-=lowbit(x);
    }
    return ans;
}
int main(){
    cin>>n>>m;
    long long s=0;
    for(int i=1;i<=n;i++){
        cin>>a[i];
        update1(i,a[i]-s);
        update2(i,(i-1)*(a[i]-s));
        s=a[i];
    }
    for(int i=1;i<=m;i++){
        cin>>t;
        if(t==1){
            cin>>x>>y>>k;
            update1(x,k);
            update1(y+1,-k);
            update2(x,k*(x-1));
            update2(y+1,-k*y);
        }
        else{
            cin>>x>>y;
            int s1=y*prefix1(y)-(x-1)*prefix1(x-1);
            int s2=prefix2(x-1)-prefix2(y);
            cout<<s1+s2<<endl;
        }
    }
    return 0;
}

by monodev @ 2024-01-06 14:48:23

@ALEX_HR_H 这题用不了树状数组,会超时


|