Cod sursa(job #2965426)

Utilizator gabriel10tm@gmail.comGabriel Marian [email protected] Data 15 ianuarie 2023 12:23:18
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <bits/stdc++.h>
using namespace std;
const int nmx = 1e5+5;
#define ll long long
ll a[nmx];
// when finished also run this using interval trees
// si cu binary search pe bits
int n;
#if 1
#define cin fin
#define cout fout
ifstream fin("aib.in");
ofstream fout("aib.out");
#endif
ll query(int i){
    ll sum = 0;
    for(;i>0;i-=i&-i)
        sum += a[i];
    return sum;
}

void update(int i, ll add){
    for(;i<=n;i+=i&-i)
        a[i] += add;
}

int main()
{
    int m;
    cin >> n >> m;
    for(int i=1;i<=n;i++){
        int x;
        cin >>x;
        update(i,x);
    }
    while(m--){
        ll op,x,y;
        cin >> op;
        if(op == 0){
            cin >> x >> y;
            update(x,y);
        }
        else if(op == 1){
            cin >> x >> y;
            cout << query(y)-query(x-1) << "\n";
        }
        else if(op == 2){
            cin >> x;
            ll st = 0, dr = n+1;
            while(st<=dr){
                int md = (st+dr)/2;
                ll res = query(md);
                if(res == x){
                    if(md == 0)
                        md = -1;
                    cout << md << "\n";
                    goto fin;
                }
                else if(res < x){
                    st = md+1;
                }
                else
                    dr = md-1;
            }
            cout << "-1\n";
            fin:{}
        }

    }

}