hdu1166(树状数组)

http://acm.hdu.edu.cn/showproblem.php?pid=1166

思路
理解树状数组后直接可以套模板

#include<iostream>
#include<cstdio>
using namespace std;

template<class T>
class Binary_Index_Tree{
public:
    T * a;
    T * c;
    int size;
    Binary_Index_Tree(T * b,int size){
        if(b==NULL) return;
        a=new T[size+1];
        c=new T[size+1];
        this->size=size+1;
        //init 
        for(int i=0;i<size+1;i++){
            a[i]=0;
            c[i]=0;
        }
        //build 
        for(int i=1;i<=size;i++){
            a[i]=b[i-1];
            add(i, a[i]);
        }
    }


    //以0起始 
    T sum(int i){
        i++;
        T sum=0;
        while(i>=1){
            sum += c[i];
            i-=lowbit(i);
        }
        return sum;
    }

    T query(int l,int r){
        T res= sum(r)-sum(l)+a[l+1];
        return res;
    }


    T get(int i){
        return a[i+1];
    }

    T set(int i,T v){
        i++;
        T d=v-a[i];
        a[i] = v;
        add(i,d);
    }

private:
    int lowbit (int x){
        return x&(-x);
    } ;

    void add(int i,T v){
        while(i>=1&&i<this->size){
            c[i]+=v;
            i+=lowbit(i);
        }
    }

};

int b[50005];
int main()
{
    int T;
    scanf("%d",&T);
    int cas=1;
    while(T--)
    {

        int n;
        scanf("%d",&n);
        for(int i=0;i<n;i++)
            scanf("%d",&b[i]);

        printf("Case %d:\n",cas++);
        int *t =b;
        Binary_Index_Tree<int>tree(t,n); 

        char str[40];
        scanf("%s",str);
        while(str[0]!='E'){
            int x,y;
            scanf("%d %d",&x,&y);

            if(str[0]=='A')
                tree.set(x-1,tree.get(x-1)+y);

            if(str[0]=='S')
                tree.set(x-1,tree.get(x-1)-y);
            if(str[0]=='Q'){
                int re=tree.query(x-1,y-1);
                printf("%d\n",re);
            }
            scanf("%s",str);
        }   

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值