溫馨提示×

利用C++樹狀數組處理大規模數據

c++
小樊
116
2024-08-19 20:54:35
欄目: 編程語言

樹狀數組(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,并使用其來處理一些數據更新和求和操作。通過樹狀數組,我們可以高效地處理大規模數據,并快速進行數據統計和查詢。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女