Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*If you are slow ,try hard and become fast
- If you are making mistakes , learn from them and correct them
- If you are weak in something , do practice and become good at it
- */
- /* Don't do just for the sake ... learn from it , that is more important */
- //Don't Think Just Do It!!
- #include <bits/stdc++.h>
- using namespace std;
- #define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL)
- #define ll long long
- #define ld long double
- #define pb push_back
- #define fe first
- #define se second
- #define st(x) sort(x.begin(),x.end())
- #define rst(x) sort(x.rbegin(), x.rend())
- #define all(x) x.begin(),x.end()
- long double pi = 3.14159265358979323;
- const double EPS = 1e-12;
- const int N = 1e5 + 5;
- const int mod = 1e9 + 7;
- // segment tree
- ll tree[N << 2];
- ll a[N];
- void build(ll l , ll r , ll node)
- {
- if(l == r){
- tree[node] = a[l];
- return ;
- }
- ll mid = ( l + r) >> 1;
- build(l,mid,node*2);
- build(mid + 1 , r , node*2 + 1);
- tree[node] = tree[node*2] + tree[node*2 + 1];
- }
- ll query(ll l , ll r ,ll node,ll ql , ll qr )
- {
- if(r < ql || l > qr)//if queury is out of the range...
- return 0 ;
- if(l >= ql && r <= qr)//important condition like if our array is of size of 8 and we are
- //quering for 1 - 6 then in second iteration for block 1 - 4;
- return tree[node];// // range represented by a node is completely inside the given range
- ll mid = (l + r) >> 1;
- ll s1 = query(l , mid ,node << 1, ql , qr );
- ll s2 = query(mid + 1 , r ,(node << 1) + 1,ql , qr );
- //learn very important note do NOT use node << 1 + 1 it will result in (node << 2)
- return s1 + s2;
- }
- void update(ll l , ll r ,ll node,ll idx,ll val)
- {
- if(l == r){
- if(l == idx){
- tree[node] += val;
- a[l] += val;
- }
- return ;
- }
- else{
- ll mid = (l + r) >> 1;
- if(idx <= mid)
- update(l , mid ,node << 1,idx,val);
- else
- update(mid + 1 , r ,(node << 1) + 1,idx,val);
- tree[node] = tree[node << 1] + tree[(node << 1) + 1];
- }
- }
- int main()
- {
- fast;
- ll n;
- cin >> n;
- for(int i = 1 ; i <= n; i++ )
- cin >> a[i];
- build(1,n,1);
- ll q;
- cin >> q;
- while(q--)
- {
- ll c;
- cin >> c;
- if(!c){
- ll ql , qr;
- cin >> ql >> qr;
- cout << query(1,n,1,ql,qr) << "\n";
- }
- else
- {
- ll idx,val;
- cin >> idx >> val;
- update(1,n,1,idx,val);
- }
- }
- //time complexity
- //build O(n)
- //query O(logn)
- //update O(logn)
- //space complexity O(n)
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment