Mobile phones-二维树状数组

update@2011-08-01

///直接套一维的 主要代码如下
int C[(1<<10)+1][(1<<10)+1] = {};

int lowbit(int x){
    return x & (x^(x-1));//这一步是把x的二进制表示中的最低位1取出来

    //x   = ***100
    //x-1 = ***011
    //x ^ (x-1) = 000111
    //x & (x ^ (x-1)) = 000100

    //return x&(-x);
    //x  = ***100
    //-x = ---011 + 1 = ---100;
    //x&-x = 000100;
}

void add(int i,int j,int v,int upper){//增加
    int t_i,t_j;
    for(t_i = x;t_i <= upper;t_i += lowbit(t_i)){
        for(t_j = y;t_j <= upper;t_j += lowbit(t_j)){
            C[t_i][t_j] += v;
        }
    }
}

int query(int i,int j){//查询
    int sum = 0;
    int t_i,t_j;
    for(t_i = i;t_i > 0;t_i -= lowbit(t_i)){
        for(t_j = j;t_j > 0;t_j -= lowbit(t_j)){
            sum += C[t_i][t_j];
        }
    }
    return sum;
}


//注意add操作和query操作
add(x+1,y+1,v,n);
printf("%d\n",query(right+1,top+1) + query(left,bottom) - query(right+1,bottom) - query(left,top+1));





题目链接:Mobile phones
简单的二维树状数组,先看一维的,到二维就很简单了。百度百科有个图,看那个图就能明白树状数组是什么样子的 以及为什么C[i] = A[i-2^k + 1]到A[i]的和,还有lowbit函数的意思