树状数组模板

树状数组模板

//树状数组存取、查询log(n),区间求和问题
int n,tree[N]; //tree数组按二进制存,根据n的末尾0的个数存取

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

int Query(int x)  //返回1到x的前缀和
{
    int res=0;
    while(x)
    {
        res+=tree[x];
        x-=lowbit(x);
    }
    return res;
}

void Add(int x,int v)  //实现a[x]+v;
{
    while(x<=n)
    {
        tree[x]+=v;
        x+=lowbit(x);
    }
}

void init()   //输入数据
{
    for(int i=1;i<=n;i++)
    {
        int x;
        scanf("%d",&x);
        Add(i,x);
    }
}

猜你喜欢

转载自blog.csdn.net/baodream/article/details/80207879