提交时间:2022-02-08 17:06:57
运行 ID: 44441
#include <iostream> #include <vector> using namespace std; inline int lowbit(const int& n) { return n & -n; } class Fenwick { private: int* tree; const int size; public: template <class Iter> Fenwick(Iter, Iter); Fenwick(const size_t&); ~Fenwick(); Fenwick& operator=(const Fenwick&); Fenwick(const Fenwick&); void update(int, int, const int&); void update(int, const int&); int get_sum(int) const; int get_sum(int, int) const; }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N(0), M(0); cin >> N; vector<int> nums(N); for (vector<int>::iterator i(nums.begin()); i != nums.end(); ++i) { cin >> *i; } Fenwick fwk(N); cin >> M; for (int i(0), option(0), pos1(0), pos2(0), val(0); i != M && cin >> option; ++i) { switch (option) { case 1: cin >> pos1 >> pos2 >> val; fwk.update(pos1, pos2, val); break; case 2: cin >> pos1; cout << (fwk.get_sum(pos1) + nums[pos1 - 1]) << endl; break; } } return 0; } template <class Iter> Fenwick::Fenwick(Iter beg, Iter end) : size(end - beg + 1) { tree = new int[size](); for (int i(1); beg != end; ++i, ++beg) { tree[i] += *beg; if (size > i + lowbit(i)) { tree[i + lowbit(i)] += tree[i]; } } } Fenwick::Fenwick(const size_t& sz) : size(sz + 1) { tree = new int[size](); } Fenwick::~Fenwick() { delete[] tree; } void Fenwick::update(int pos, const int& val) { while (pos < size) { tree[pos] += val; pos += lowbit(pos); } } void Fenwick::update(int beg, int end, const int& val) { update(beg, val), update(end + 1, -val); } int Fenwick::get_sum(int pos) const { int sum(0); while (pos) { sum += tree[pos]; pos -= lowbit(pos); } return sum; } int Fenwick::get_sum(int beg, int end) const { return get_sum(end) - get_sum(beg - 1); }