GastonFontenla

Untitled

Sep 25th, 2019
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.01 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. #define ll long long
  6.  
  7. const int MAX_N = 200001;
  8. ll ST[MAX_N*4];
  9. int leftmost[MAX_N*4];
  10. int rightmost[MAX_N*4];
  11. int n;
  12.  
  13. int sigPot2(int val)
  14. {
  15.     int p = 1;
  16.     while(p < val)
  17.         p *= 2;
  18.     return p;
  19. }
  20.  
  21. ll query(int nodo, int l, int r)
  22. {
  23.     ///nodo representa el rango [leftmost[nodo], rightmost[nodo]]
  24.     ///Chequeo si no se superponen
  25.     if(rightmost[nodo] < l || r < leftmost[nodo])
  26.         return 0;
  27.  
  28.     ///Si está completamente contenido
  29.     if(l <= leftmost[nodo] && rightmost[nodo] <= r)
  30.         return ST[nodo];
  31.  
  32.     return query(nodo*2, l, r) + query(nodo*2+1, l, r);
  33. }
  34.  
  35. void update(int pos, int val)
  36. {
  37.     ///Actualizar el valor de la hoja
  38.     ST[pos] = val;
  39.  
  40.     ///Actualizar los nodos que me llevan a la raiz
  41.     while(pos > 1)
  42.     {
  43.         pos /= 2;
  44.         ST[pos] = ST[pos*2] + ST[pos*2+1];
  45.     }
  46. }
  47.  
  48. int main()
  49. {
  50.     int q;
  51.     cin >> n >> q;
  52.  
  53.     vector <int> x(n);
  54.  
  55.     for(int i=0; i<n; i++)
  56.         cin >> x[i];
  57.  
  58.     n = sigPot2(n);
  59.     x.resize(n, 0);
  60.  
  61.     ///Agregar los valores del input en las hojas del ST
  62.     for(int i=0; i<x.size(); i++)
  63.         ST[n+i] = x[i];
  64.  
  65.     ///Inicializo el resto del ST en cero
  66.     for(int i=0; i<n; i++)
  67.         ST[i] = 0;
  68.  
  69.     ///Precalculando leftmost y rightmost
  70.     for(int i=n; i<n*2; i++)
  71.         leftmost[i] = rightmost[i] = i;
  72.  
  73.     for(int i=n-1; i>=1; i--)
  74.     {
  75.         leftmost[i] = leftmost[i*2];
  76.         rightmost[i] = rightmost[i*2+1];
  77.     }
  78.  
  79.     ///Precálculo del ST
  80.     for(int i=n-1; i>=1; i--)
  81.         ST[i] = ST[i*2] + ST[i*2+1];
  82.  
  83.     int l, r, pos, val, tipo;
  84.     for(int i=0; i<q; i++)
  85.     {
  86.         cin >> tipo;
  87.         if(tipo == 1)
  88.         {
  89.             ///Actualizar valor
  90.             cin >> pos >> val;
  91.             update(pos+n-1, val);
  92.         }
  93.         else
  94.         {
  95.             ///Responder rango
  96.             cin >> l >> r;
  97.             cout << query(1, l+n-1, r+n-1) << endl;
  98.         }
  99.     }
  100.  
  101.     return 0;
  102. }
Add Comment
Please, Sign In to add comment