树状数组 单点修改 区间查询

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
using namespace std;
int n,m;
int c[500005];
int lowbit(int x)
{
    return (-x)&x;
}
void add(int pos,int x)
{
    while(pos<=n)
    {
        c[pos]+=x;
        pos+=lowbit(pos);
    }
}
void input()
{
    int x;
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&x);
        add(i,x);
    }
}
int query(int pos)
{
    int res=0;
    while(pos>0)
    {
        res+=c[pos];
        pos-=lowbit(pos);
    }
    return res;
}
int main()
{
    scanf("%d%d",&n,&m);
    input();
    int f,x,y;
    for(int i=1;i<=m;i++)
    {
        scanf("%d%d%d",&f,&x,&y);
        if(f==1)
        add(x,y);
        else if(f==2)
        cout<<query(y)-query(x-1)<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41603898/article/details/89074614