Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- std::vector<int> InitArray(int n) {
- std::vector<int> res;
- int temp = 0;
- for (int i = 0; i < n; ++i) {
- std::cin >> temp;
- res.push_back(temp);
- }
- return res;
- }
- class Fenwick3D {
- public:
- Fenwick3D(std::vector<int> initarray) {
- arr_ = initarray;
- for (int i = 0; i < initarray.size(); ++i) {
- if (i % 2 != 0) {
- arr_[i] = -arr_[i];
- }
- tree_.push_back(0);
- }
- for (int i = 0; i < initarray.size(); ++i) {
- for (int j = F(i) - 1; j <= i; ++j) {
- if (j < 0) {
- continue;
- }
- tree_[i] += arr_[j];
- }
- }
- }
- int GetSum(int left, int right) const {
- int value1 = PrefixSum(right);
- int value2 = PrefixSum(left - 1);
- return value1 - value2;
- }
- void Update(int index, int value) {
- int temp = arr_[index];
- if (index % 2 != 0) {
- temp = -temp;
- }
- int delta = value - temp;
- UpdateDelta(index, delta);
- arr_[index] = value;
- }
- private:
- static int F(int i) { return (i & (i + 1)); }
- static int G(int i) { return (i | (i + 1)); }
- int PrefixSum(int index) const {
- int answer = 0;
- for (int x = index; x >= 0; x = F(x) - 1) {
- answer += tree_[x];
- }
- return answer;
- }
- void UpdateDelta(int index, int delta) {
- const int kSize = static_cast<int>(arr_.size());
- for (int x = index; x < kSize; x = G(x)) {
- if (x % 2 != 0) {
- tree_[x] -= delta;
- } else {
- tree_[x] += delta;
- }
- }
- }
- std::vector<int> tree_;
- std::vector<int> arr_;
- };
- void Requests() {
- int n = 0;
- std::cin >> n;
- std::vector<int> base = InitArray(n);
- Fenwick3D fenwick(base);
- int v = 0;
- int l = 0;
- int r = 0;
- int m = 0;
- std::cin >> m;
- for (int k = 0; k < m; ++k) {
- std::cin >> v;
- if (v == 0) {
- std::cin >> l >> r;
- fenwick.Update(l - 1, r);
- } else if (v == 1) {
- std::cin >> l >> r;
- std::cout << fenwick.GetSum(l - 1, r - 1) << "\n";
- }
- }
- }
- int main() {
- Requests();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement