温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++ set在树状数组实现中的简化

发布时间:2024-08-05 17:10:04 来源:亿速云 阅读:80 作者:小樊 栏目:编程语言

在树状数组实现中,我们通常需要维护一个数组和一个set来记录元素的插入和删除操作。通过使用C++的set数据结构,我们可以简化这个过程,只需要维护一个set即可完成元素的插入和删除操作。

下面是一个使用C++ set实现的树状数组简化代码示例:

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

class FenwickTree {
private:
    set<int> tree;
public:
    void update(int idx, int val) {
        while (idx <= tree.size()) {
            tree.insert(idx);
            idx += idx & -idx;
        }
    }

    int query(int idx) {
        int sum = 0;
        auto it = tree.lower_bound(idx);
        while (it != tree.begin()) {
            sum += *it;
            it--;
            idx -= idx & -idx;
        }
        return sum;
    }
};

int main() {
    FenwickTree ft;
    ft.update(1, 1);
    ft.update(2, 2);
    ft.update(3, 3);
    cout << ft.query(3) << endl; // Output: 6
    return 0;
}

在这个简化的实现中,我们使用一个set来代替传统的数组,通过set的lower_bound函数来查找元素的位置。这样可以简化代码实现,并且提高了代码的可读性。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI