复制
收藏
提问
简洁

C++ 树状数组模版

337cbbdee
1周前
全网
文档
学术
百科
知识库
时间不限
自动
回答简洁模式
深入研究一些
  • 树状数组是一种高效的数据结构,适用于处理区间更新和查询问题。
  • 树状数组模板

#include <iostream>
#include <vector>
using namespace std;

class FenwickTree {
private:
    vector<int> tree;
    int n;

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

public:
    FenwickTree(int size) : n(size), tree(size + 1, 0) {}

    void update(int idx, int delta) {
        while (idx <= n) {
            tree[idx] += delta;
            idx += lowbit(idx);
        }
    }

    int query(int idx) {
        int sum = 0;
        while (idx > 0) {
            sum += tree[idx];
            idx -= lowbit(idx);
        }
        return sum;
    }

    int range_query(int l, int r) {
        return query(r) - query(l - 1);
    }
};

int main() {
    FenwickTree ft(10); // 初始化大小为10的树状数组
    ft.update(3, 5); // 更新索引3的值为5
    cout << "Sum from index 1 to 5: " << ft.range_query(1, 5) << endl; // 查询区间和
    return 0;
}
  • 要点总结:树状数组通过lowbit运算简化区间查询和更新操作,提高效率。12345678
你觉得结果怎么样?
树状数组与线段树的区别是什么?
如何优化树状数组的性能?
树状数组在实际应用中有哪些限制?
如何优化树状数组的查询效率?
树状数组的lowbit运算如何实现?
树状数组在处理大数据量时的性能如何?

以上内容由AI搜集生成,仅供参考

在线客服