Advertisement
Josif_tepe

Untitled

Feb 12th, 2023
849
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_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_tree(L, mid, 2 * position);
  20.         build_tree(mid + 1, R, 2 * position + 1);
  21.        
  22.         segment_tree[position] = segment_tree[2 * position] + segment_tree[2 * position + 1];
  23.     }
  24.    
  25. }
  26. // L R i L R j L R
  27. ll query(int L, int R, int position, int i, int j) {
  28.     if(R < i or j < L) {
  29.         return 0;
  30.     }
  31.     if(i <= L and R <= j) {
  32.         return segment_tree[position];
  33.     }
  34.     int mid = (L + R) / 2;
  35.     return query(L, mid, 2 * position, i, j) + query(mid + 1, R, 2 * position + 1, i, j);
  36. }
  37. int main() {
  38.     ios_base::sync_with_stdio(false);
  39.     int n, q;
  40.     cin >> n >> q;
  41.    
  42.     for(int i = 0; i < n; i++) {
  43.         cin >> a[i];
  44.     }
  45.    
  46.     build_tree(0, n - 1, 1); // build the segment tree
  47.    
  48.     for(int i = 0; i < q; i++) {
  49.         int x, y;
  50.         cin >> x >> y;
  51.         x--; y--;
  52.        
  53.         cout << query(0, n - 1, 1, x, y) << endl;
  54.     }
  55.    
  56.    
  57.     return 0;
  58. }
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement