Advertisement
Josif_tepe

Untitled

Feb 13th, 2023
902
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.98 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <set>
  5. #include <cmath>
  6. #include <map>
  7. #include <cstring>
  8. using namespace std;
  9. const int maxn = 2e5 + 10;
  10. typedef long long ll;
  11. int arr[maxn];
  12. ll segment_tree[3 * maxn];
  13.  
  14. void build_tree(int L, int R, int position) {
  15.     if(L == R) {
  16.         segment_tree[position] = arr[L];
  17.     }
  18.     else {
  19.         int middle = (L + R) / 2;
  20.         build_tree(L, middle, 2 * position);
  21.         build_tree(middle + 1, R, 2 * position + 1);
  22.         segment_tree[position] = segment_tree[2 * position] + segment_tree[2 * position + 1];
  23.     }
  24. }
  25. //  L R i L R j L R
  26. ll query(int L, int R, int position, int i, int j) {
  27.     if(i <= L and R <= j) {
  28.         return segment_tree[position];
  29.     }
  30.     if(R < i or j < L) {
  31.         return 0;
  32.     }
  33.     int middle = (L + R) / 2;
  34.     return query(L, middle, 2 * position, i, j) + query(middle + 1, R, 2 * position + 1, i, j);
  35. }
  36. void update(int L, int R, int position, int idx, int new_value) {
  37.     if(L == R) {
  38.         segment_tree[position] = new_value;
  39.         return;
  40.     }
  41.     int middle = (L + R) / 2;
  42.     if(idx <= middle) {
  43.         update(L, middle, 2 * position, idx, new_value);
  44.     }
  45.     else {
  46.         update(middle + 1, R, 2 * position + 1, idx, new_value);
  47.     }
  48.     segment_tree[position] = segment_tree[2 * position] + segment_tree[2 * position + 1];
  49. }
  50.  
  51. int main() {
  52.     ios_base::sync_with_stdio(false);
  53.     int n, q;
  54.     cin >> n >> q;
  55.    
  56.     for(int i = 0; i < n; i++) {
  57.         cin >> arr[i];
  58.     }
  59.     build_tree(0, n - 1, 1);
  60.    
  61.     for(int i = 0; i < q; i++) {
  62.         int type_query;
  63.         cin >> type_query;
  64.        
  65.         if(type_query == 1) {
  66.             int k, u;
  67.             cin >> k >> u;
  68.             update(0, n - 1, 1, k - 1, u);
  69.         }
  70.         else {
  71.             int a, b;
  72.             cin >> a >> b;
  73.             a--; b--;
  74.            
  75.             cout << query(0, n - 1, 1, a, b) << endl;
  76.         }
  77.     }
  78.     return 0;
  79. }
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement