本文共 1572 字,大约阅读时间需要 5 分钟。
为了解决这个问题,我们需要处理一个长度为N的数列,并对它执行M次操作。操作有两种类型:一种是将某个位置的数加上一个值,另一种是求某个区间内所有数的和。为了高效处理这些操作,我们使用Fenwick树(Binary Indexed Tree)来实现。
问题分析:
Fenwick树的实现:
算法步骤:
#include#include #include #include #include #include using namespace std; class FenwickTree { private: vector tree; int size; public: FenwickTree(int s) : tree(s + 2), size(s) {} void update(int x, int delta) { while (x <= size) { tree[x] += delta; x += lowbit(x); } } int get_sum(int x) { int res = 0; while (x > 0) { res += tree[x]; x -= lowbit(x); } return res; } }; int lowbit(int t) { return t & (-t); } int main() { int n, m; scanf("%d %d", &n, &m); vector c(n + 2, 0); // 1-based indexing for (int i = 1; i <= n; ++i) { scanf("%d", &c[i]); } FenwickTree ft(n); for (int i = 1; i <= n; ++i) { ft.update(i, c[i]); } for (int i = 0; i < m; ++i) { int a, x, y; scanf("%d %d %d", &a, &x, &y); if (a == 1) { ft.update(x, y); } else { int sum_y = ft.get_sum(y); int sum_x_1 = ft.get_sum(x - 1); int res = sum_y - sum_x_1; cout << res << endl; } } return 0; }
FenwickTree类:
tree。update方法用于对某个位置进行点更新。get_sum方法用于计算前缀和,用于区间和查询。lowbit函数:
主函数:
update,区间和查询使用get_sum计算。这种方法确保了每个操作的时间复杂度为O(logN),能够高效处理大规模数据。
转载地址:http://iaqfk.baihongyu.com/