c++ - 如何使用二叉索引树来计算小于索引值的元素数?

标签 c++ algorithm fenwick-tree

问题是计算小于索引后值的值的个数。这是代码,但我不明白如何使用二叉索引树来执行此操作?

#include <iostream>
#include <vector>
#include <algorithm>
#define LL long long
#define MOD 1000000007
#define MAXN 10
using namespace std;
typedef pair<int, int> ii;
int BIT[MAXN+1];
int a[MAXN+1];
vector< ii > temp;
int countSmallerRight[MAXN+1];
int read(int idx) {
    int sum = 0;
    while (idx > 0) {
    sum += BIT[idx];
    idx -= (idx & -idx);
    }
    return sum;
}
void update(int idx, int val) {
    while (idx <= MAXN) {
    BIT[idx] += val;
    idx += (idx & -idx);
    }
}
int main(int argc, const char * argv[])
{
int N;

scanf("%d", &N);

 for (int i = 1; i <= N; i++) {
    scanf("%d", &a[i]);
    temp.push_back(ii(a[i], i));
    }

sort(temp.begin(), temp.end());
countSmallerRight[temp[0].second] = 0;
update(1, 1);
update(temp[0].second, -1);

for (int i = 1; i < N; i++) {
    countSmallerRight[temp[i].second] = read(temp[i].second);
    update(1, 1);
    update(temp[i].second, -1);
}
for (int i = 1; i <= N; i++) {
    printf("%d,", countSmallerRight[i]);
}


putchar('\n');


return 0;


}

如果有人能解释代码的工作原理,那将会很有帮助。

最佳答案

了解BIT this是最好的链接之一。
TC 给出了你使用的功能的完整解释,但其余部分是如何使用它的逻辑。
基本理解:

ques: there are n heaps and in each heap initially there are 1 stones then we add stones from u to v…find how much stone are there in given heap.

解决方案,每次迭代的答案是 http://pastebin.com/9QJ589VR . 理解之后,尝试实现你的问题。

关于c++ - 如何使用二叉索引树来计算小于索引值的元素数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21234399/

相关文章:

c++ - 确定时间关键循环中 200 毫秒卡住的原因

algorithm - 如何处理重复出现的时间?

java - 如何交换数组中最大的数字和最后一个数字?

algorithm - 计算连续糖果的数量

c++ - 使用二叉索引树的字符串查询

c++ - 在 Qt 拖放中使用 QMimeData 传递数据

c++ - 如何在 C++ 中将 int 参数放入 Sigleton 构造函数

c++ - 二维数组在退出循环后移除其元素

java - 有没有比 Java 中的 Collections.sort() 更快的东西?

c++ - (number & -number) 在位编程中是什么意思?