Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- #define ll long long
- const int MAX_N = 200001;
- ll ST[MAX_N*4];
- int leftmost[MAX_N*4];
- int rightmost[MAX_N*4];
- int n;
- int sigPot2(int val)
- {
- int p = 1;
- while(p < val)
- p *= 2;
- return p;
- }
- ll query(int nodo, int l, int r)
- {
- ///nodo representa el rango [leftmost[nodo], rightmost[nodo]]
- ///Chequeo si no se superponen
- if(rightmost[nodo] < l || r < leftmost[nodo])
- return 0;
- ///Si está completamente contenido
- if(l <= leftmost[nodo] && rightmost[nodo] <= r)
- return ST[nodo];
- return query(nodo*2, l, r) + query(nodo*2+1, l, r);
- }
- void update(int pos, int val)
- {
- ///Actualizar el valor de la hoja
- ST[pos] = val;
- ///Actualizar los nodos que me llevan a la raiz
- while(pos > 1)
- {
- pos /= 2;
- ST[pos] = ST[pos*2] + ST[pos*2+1];
- }
- }
- int main()
- {
- int q;
- cin >> n >> q;
- vector <int> x(n);
- for(int i=0; i<n; i++)
- cin >> x[i];
- n = sigPot2(n);
- x.resize(n, 0);
- ///Agregar los valores del input en las hojas del ST
- for(int i=0; i<x.size(); i++)
- ST[n+i] = x[i];
- ///Inicializo el resto del ST en cero
- for(int i=0; i<n; i++)
- ST[i] = 0;
- ///Precalculando leftmost y rightmost
- for(int i=n; i<n*2; i++)
- leftmost[i] = rightmost[i] = i;
- for(int i=n-1; i>=1; i--)
- {
- leftmost[i] = leftmost[i*2];
- rightmost[i] = rightmost[i*2+1];
- }
- ///Precálculo del ST
- for(int i=n-1; i>=1; i--)
- ST[i] = ST[i*2] + ST[i*2+1];
- int l, r, pos, val, tipo;
- for(int i=0; i<q; i++)
- {
- cin >> tipo;
- if(tipo == 1)
- {
- ///Actualizar valor
- cin >> pos >> val;
- update(pos+n-1, val);
- }
- else
- {
- ///Responder rango
- cin >> l >> r;
- cout << query(1, l+n-1, r+n-1) << endl;
- }
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment