C++树状数组

 

#include
#include

using namespace std;

int lowbit(int n) {
    return n - (n & (n - 1));
}
/**
 *
原始数组的i位置增加v后,更新c数组
 */
void update(int n, int i, int v, int c[]) {
    for (int k = i; k <= n; k += lowbit(k)) {
        c[k] += v;
    }
}

int getSum(int c[], int i) {
    int sum = 0;
    for (int k = i; k >= 1; k -= lowbit(k)) {
        sum += c[k];
    }
    return sum;
}

int main() {
    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
    int c[9];
    memset(c, 0, sizeof(c));
    for (int i = 0; i < 8; ++i) {
        update(9, i + 1, arr[i], c);
    }
    cout << getSum(c, 5) << endl;
    cout << getSum(c, 6) << endl;
    cout << getSum(c, 7) - getSum(c, 4) << endl;

    return 0;
}

C++树状数组_第1张图片

你可能感兴趣的:(C++树状数组)