樹狀數組(Fenwick Tree)是一種用于高效處理動態區間和的數據結構,可以用來解決一些統計問題,比如求區間和、區間最大值、區間最小值等。在處理大規模數據時,樹狀數組可以幫助我們高效地進行數據統計和查詢。
下面是一個使用C++實現樹狀數組的示例代碼:
#include <iostream>
#include <vector>
using namespace std;
// 樹狀數組的實現
class FenwickTree {
public:
FenwickTree(int n) {
tree.resize(n + 1, 0);
}
void update(int index, int delta) {
while (index < tree.size()) {
tree[index] += delta;
index += index & -index;
}
}
int query(int index) {
int sum = 0;
while (index > 0) {
sum += tree[index];
index -= index & -index;
}
return sum;
}
private:
vector<int> tree;
};
int main() {
int n = 10; // 數據規模
FenwickTree tree(n);
// 更新元素
tree.update(1, 2);
tree.update(2, 3);
tree.update(3, 5);
// 查詢區間和
cout << tree.query(3) << endl; // 輸出:10
cout << tree.query(5) - tree.query(2) << endl; // 輸出:8
return 0;
}
在上面的示例代碼中,我們實現了一個簡單的樹狀數組類FenwickTree,并使用其來處理一些數據更新和求和操作。通過樹狀數組,我們可以高效地處理大規模數據,并快速進行數據統計和查詢。