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

在树状数组实现中,我们通常需要维护一个数组和一个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函数来查找元素的位置。这样可以简化代码实现,并且提高了代码的可读性。

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

评论

有免费节点资源,我们会通知你!加入纸飞机订阅群

×
天气预报查看日历分享网页手机扫码留言评论Telegram