Josif_tepe

Untitled

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