模板【洛谷P3368】 【模板】树状数组 2

P3368 【模板】树状数组 2

如题,已知一个数列,你需要进行下面两种操作:

1.将某区间每一个数数加上x

2.求出某一个数的值

树状数组区间加,单点查询。

code:

#include <iostream>
#include <cstdio>

using namespace std;

const int wx=500017;

inline int read(){
    int sum=0,f=1; char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1; ch=getchar();}
    while(ch>='0'&&ch<='9'){sum=(sum<<1)+(sum<<3)+ch-'0'; ch=getchar();}
    return sum*f;
}

int sum[wx],n,m;

void add(int pos,int k){
    for(int i=pos;i<=n;i+=(i&-i))
        sum[i]+=k;
}

int query(int pos){
    int re=0;
    for(int i=pos;i>=1;i-=(i&-i))
        re+=sum[i];
    return re;
}

void add_wx(int l,int r,int k){
    add(l,k); add(r+1,-k);
}

int main(){
    n=read(); m=read();
    for(int i=1;i<=n;i++){
        int x; x=read();
        add(i,x); add(i+1,-x);
    }
    for(int i=1;i<=m;i++){
        int opt; opt=read();
        if(opt==1){
            int x,y,k;
            x=read(); y=read(); k=read();
            add_wx(x,y,k);
        }
        else{
            int x; x=read();
            printf("%d\n",query(x));
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/wangxiaodai/p/9880850.html