Advertisement
Josif_tepe

Untitled

Feb 12th, 2023
833
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <set>
  5. #include <cmath>
  6. #include <map>
  7. using namespace std;
  8. const int maxn = 2e5 + 10;
  9. typedef long long ll;
  10. int a[maxn];
  11. ll segment_tree[3 * maxn];
  12.  
  13. void build_segment_tree(int L, int R, int position) {
  14.     if(L == R) {
  15.         segment_tree[position] = a[L];
  16.     }
  17.     else {
  18.         int mid = (L + R) / 2;
  19.         build_segment_tree(L, mid, 2 * position);
  20.         build_segment_tree(mid + 1, R, 2 * position + 1);
  21.         segment_tree[position] = segment_tree[2 * position] + segment_tree[2 * position + 1];
  22.     }
  23. }
  24. // L R i L R j L R
  25. ll query(int L, int R, int position, int i, int j) {
  26.     if(R < i or j < L) {
  27.         return 0;
  28.     }
  29.     if(i <= L and R <= j) {
  30.         return segment_tree[position];
  31.     }
  32.     int middle = (L + R) / 2;
  33.     return query(L, middle, 2 * position, i, j) + query(middle + 1, R, 2 * position + 1, i, j);
  34. }
  35.  
  36. int main() {
  37.     ios_base::sync_with_stdio(false);
  38.     int n, q;
  39.     cin >> n >> q;
  40.    
  41.     for(int i = 0; i < n; i++) {
  42.         cin >> a[i];
  43.     }
  44.    
  45.     build_segment_tree(0, n - 1, 1);
  46.     for(int i = 0; i < q; i++) {
  47.         int x, y;
  48.         cin >> x >> y;
  49.         x--; y--;
  50.        
  51.         cout << query(0, n - 1, 1, x, y) << endl;
  52.        
  53.        
  54.     }
  55.     return 0;
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement