一个简单的整数问题【树状数组】【维护前缀和】

题目传送门

树状数组可以维护前缀和
区级更新可以差分数组的思想
单点查询 正常查询

#include<iostream>
#include<algorithm>
using namespace std;
const int N=1e5+100;
typedef long long ll;
//树状数组维护b的前缀和
ll a[N],b[N];
int n,m;
ll lowbit(ll x)
{
    return x&-x;
}

void add(ll x,ll y)
{
    for(;x<=n;x+=lowbit(x))
    {
        b[x]+=y;
    }
}
ll ask(ll x)
{
    ll res=0;
    for(;x;x-=lowbit(x))
    {
        res+=b[x];
    }
    return res;
}

int main()
{
    cin>>n>>m;
    for(int i=1;i<=n;i++) cin>>a[i];
    while(m--)
    {
        //cout<<m<<endl;
        char op;
        cin>>op;
        if(op=='Q'){
            int pos;
            cin>>pos;

            cout<<ask(pos)+a[pos]<<endl;
        }else{
            int l,r,d;
            cin>>l>>r>>d;
            add(l,d);
            add(r+1,-d);
        }

    }
    return 0;
}

发布了152 篇原创文章 · 获赞 4 · 访问量 3884

猜你喜欢

转载自blog.csdn.net/qq_43716912/article/details/100173495