( 数据结构专题 )【 树状数组 】

( 数据结构专题 )【 树状数组 】

先学一个,之后用到再学。

单点修改,区间求和

#include 
#define l(x) (x&(-x))

using namespace std;

int tree[1005];
int n = 10;

void update( int i, int date )
{
    for ( ;i<=n;i+=l(i) ) tree[i]+=date;
}

int query( int i ) // 求区间[1,i]
{
    int sum = 0;
    while ( i>0 ) {
        sum += tree[i];
        i -= l(i);
    }
    return sum;
}

int main()
{
    for ( int i=1; i<=10; i++ ) {
        update(i,i);
    }
    cout << query(4) - query(1) ;

    return 0;
}

 

 

你可能感兴趣的:(算法树之数据结构)