一个简单的整数问题【拆分+树状数组】

一个简单的整数问题【拆分+树状数组】

ACwing242

#include<bits/stdc++.h>
using namespace std;

#define int long long
const int N = 2e5;

int tree[N + 5],a[N + 5];   //分别存储树状数组、拆分前的序列
int n,q,x,y,z;
char ch;

void update(int x,int y){
    
       //更新树状数组
    for(;x <= n;x += x & -x)
        tree[x] += y;
}
int get_sum(int x){
    
             //求前缀和(求某个位置的值)
    int ans = 0;
    for(;x;x -= x & -x)
        ans += tree[x];
    return ans;
}
signed main(){
    
    
    cin>>n>>q;
    for(int i = 1;i <= n;++i){
    
    
        cin>>a[i];
        update(i,a[i] - a[i - 1]);  //拆分之后建立树状数组
    }
    while(q--){
    
    
        cin>>ch;
        if(ch == 'C'){
    
    
            cin>>x>>y>>z;
            update(x,z);                //x之后的数都加上了z
            update(y + 1,-z);           //y+1之后的数都减去z,和上一行加的z抵消
        }
        else{
    
    
            cin>>x;
            cout<<get_sum(x)<<"\n";
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45985728/article/details/123370214