Advertisement
skimono

Untitled

May 30th, 2023
558
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.82 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. struct FenwickTree {
  8.     vector <int> t;
  9.     FenwickTree(vector <int>& a) {
  10.         t.resize(a.size(), 0);
  11.         for (int i = 0; i < a.size(); i++) {
  12.             update(i, a[i]);
  13.         }
  14.     }
  15.     void update(int i, int d) {
  16.         while (i < t.size()) {
  17.             t[i] += d;
  18.             i = (i | (i + 1));
  19.         }
  20.     }
  21.  
  22.     int get_p(int i) {
  23.         int result = 0;
  24.         while (i >= 0) {
  25.             result += t[i];
  26.             i = (i & (i + 1)) - 1;
  27.         }
  28.         return result;
  29.     }
  30.     int get(int l, int r) {
  31.         return get_p(r) - get_p(l - 1);
  32.     }
  33. };
  34.  
  35. int main() {
  36.     int n;
  37.     cin >> n;
  38.     vector <int> a(n);
  39.     for (int i = 0; i < n; i++) {
  40.         cin >> a[i];
  41.     }
  42.     FenwickTree tree(a);
  43.     int k;
  44.     cin >> k;
  45.     for (int i = 0; i < k; i++) {
  46.         int l, r;
  47.         cin >> l >> r;
  48.         cout << tree.get(l - 1, r - 1) << '\n';
  49.     }
  50.     return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement