Advertisement
rudolf222222

Untitled

Nov 13th, 2022
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.08 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. std::vector<int> InitArray(int n) {
  5.   std::vector<int> res;
  6.   int temp = 0;
  7.   for (int i = 0; i < n; ++i) {
  8.     std::cin >> temp;
  9.     res.push_back(temp);
  10.   }
  11.   return res;
  12. }
  13. class Fenwick3D {
  14.  public:
  15.   Fenwick3D(std::vector<int> initarray) {
  16.     arr_ = initarray;
  17.     for (int i = 0; i < initarray.size(); ++i) {
  18.       if (i % 2 != 0) {
  19.         arr_[i] = -arr_[i];
  20.       }
  21.       tree_.push_back(0);
  22.     }
  23.     for (int i = 0; i < initarray.size(); ++i) {
  24.       for (int j = F(i) - 1; j <= i; ++j) {
  25.         if (j < 0) {
  26.           continue;
  27.         }
  28.         tree_[i] += arr_[j];
  29.       }
  30.     }
  31.   }
  32.   int GetSum(int left, int right) const {
  33.     int value1 = PrefixSum(right);
  34.     int value2 = PrefixSum(left - 1);
  35.     return value1 - value2;
  36.   }
  37.   void Update(int index, int value) {
  38.     int temp = arr_[index];
  39.     if (index % 2 != 0) {
  40.       temp = -temp;
  41.     }
  42.     int delta = value - temp;
  43.     UpdateDelta(index, delta);
  44.     arr_[index] = value;
  45.   }
  46.  
  47.  private:
  48.   static int F(int i) { return (i & (i + 1)); }
  49.   static int G(int i) { return (i | (i + 1)); }
  50.   int PrefixSum(int index) const {
  51.     int answer = 0;
  52.     for (int x = index; x >= 0; x = F(x) - 1) {
  53.       answer += tree_[x];
  54.     }
  55.     return answer;
  56.   }
  57.   void UpdateDelta(int index, int delta) {
  58.     const int kSize = static_cast<int>(arr_.size());
  59.     for (int x = index; x < kSize; x = G(x)) {
  60.       if (x % 2 != 0) {
  61.         tree_[x] -= delta;
  62.       } else {
  63.         tree_[x] += delta;
  64.       }
  65.     }
  66.   }
  67.   std::vector<int> tree_;
  68.   std::vector<int> arr_;
  69. };
  70.  
  71. void Requests() {
  72.   int n = 0;
  73.   std::cin >> n;
  74.   std::vector<int> base = InitArray(n);
  75.   Fenwick3D fenwick(base);
  76.   int v = 0;
  77.   int l = 0;
  78.   int r = 0;
  79.   int m = 0;
  80.   std::cin >> m;
  81.   for (int k = 0; k < m; ++k) {
  82.     std::cin >> v;
  83.     if (v == 0) {
  84.       std::cin >> l >> r;
  85.       fenwick.Update(l - 1, r);
  86.     } else if (v == 1) {
  87.       std::cin >> l >> r;
  88.       std::cout << fenwick.GetSum(l - 1, r - 1) << "\n";
  89.     }
  90.   }
  91. }
  92. int main() {
  93.   Requests();
  94.   return 0;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement