树状数组2——区间更新、单点查询模板

题目链接

题意:

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

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

2.求出某一个数的值

题解:

树状数组维护差分数组,树状数组的作用就是求前缀和

进行区间更新和单点查询

代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6+5;
int n,m;
int c[maxn],a[maxn];

void updata(int pos,int x)
{
    for(;pos<=n;pos+=pos&-pos)c[pos]+=x;
}
int query(int pos)
{
    int ans=0;
    for(;pos;pos-=pos&-pos)ans+=c[pos];
    return ans;
}

int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
        updata(i,a[i]-a[i-1]);
    }
    while(m--)
    {
        int op;
        scanf("%d",&op);
        if(op==1)
        {
            int x,y,k;
            scanf("%d%d%d",&x,&y,&k);
            updata(x,k);
            updata(y+1,-k);
        }
        else
        {
            int x;
            scanf("%d",&x);
            int ans=query(x);
            printf("%d\n",ans);
        }
    }
    return 0;
}
View Code

猜你喜欢

转载自www.cnblogs.com/j666/p/11734405.html
今日推荐