HDU1166 (树状数组)

模板题。 

#include<bits/stdc++.h>
using namespace std;
#define inf 0x3f3f3f3f
#define ll long long
const int maxn=50005;
const double eps=1e-8;
int tree[maxn];
inline int lowbit(int x)
{
    return x&-x;
}
void add(int x,int value) //输入数据时,需要调用此函数加到tree[]里面
{
    for(int i=x;i<=maxn;i+=lowbit(i))
    {
        tree[i]+=value;
    }
}
int get(int x) //获取的是tree[1]+……+tree[x]的值
{
    int sum=0;
    for(int i=x;i;i-=lowbit(i))
    {
        sum+=tree[i];
    }
    return sum;
}
int main()
{
    int t,cas=0;
    cin>>t;
    while(t--)
    {
        int n,d;
        cin>>n;
        memset(tree,0,sizeof(tree));
        for(int i=1;i<=n;i++)
        {
            cin>>d;
            add(i,d);
        }
        char q[10];
        cout<<"Case "<<++cas<<":"<<endl;
        while(cin>>q&&q[0]!='E')
        {
            int a,b;
            cin>>a>>b;
            if(q[0]=='Q')
            {
                cout<<get(b)-get(a-1)<<endl;
            }
            else if(q[0]=='A')
            {
                add(a,b);
            }
            else if(q[0]=='S')
            {
                add(a,-b);
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/dilly__dally/article/details/81141539
今日推荐