【模版题】树状数组(单点修改+区间查询)

版权声明:转载请注明出处哦~ https://blog.csdn.net/Cassie_zkq/article/details/88805889

不知道是哪里的题,反正是道最最基础的模版题

代码:

#include <iostream>
#include <algorithm>
#include <string.h>
#include <ctype.h>
#include <set>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <fstream>
#define  maxn 1000005
#define lowbit(x) ((x)&(-x))
typedef long long ll;
using namespace std;
ll c[maxn]={0},n,m,v,pos;
void update(int pos,int v)
{
    for(int i=pos;i<=n;i+=lowbit(i))
        c[i]+=v;
}
ll getsum(int pos)
{
    ll sum=0;
    for(int i=pos;i>0;i-=lowbit(i))
        sum+=c[i];
    return sum;
}
int main()
{
    //freopen("/Users/zhangkanqi/Desktop/11.txt","r",stdin);
    string s;
    scanf("%lld %lld",&n,&m);
    while(m--)
    {
        cin>>s>>pos>>v;
        if(s=="Add")
        {
            update(pos,v);
        }
        if(s=="Sub")
        {
            update(pos,-v);
        }
        if(s=="Ask")
        {
            int l=pos,r=v;
            printf("%lld\n",getsum(r)-getsum(l-1));
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Cassie_zkq/article/details/88805889