Advertisement
Josif_tepe

Untitled

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