Cod sursa(job #2926781)

Utilizator SeracovanuEdwardSeracovanu Edward SeracovanuEdward Data 18 octombrie 2022 18:29:34
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <bits/stdc++.h>

using namespace std;

int const nmax = 1e5 + 5;

int n , q , S[nmax];

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

int sum(int x){
int ans = 0;
while(x > 0){
    ans += S[x];
    x -= x & (-x);
}
return ans;
}

int caut(int x)
{
    int i, step;

    for (step = 1; step <= n; step <<= 1);

    for (i = 1; step; step >>= 1)
        if (i + step <= n && sum(i + step) <= x)
           i += step;
    if(sum(i) == x)
        return i;
    return -1;
}

int main()
{
    freopen("aib.in" , "r" , stdin);
    freopen("aib.out" , "w" ,stdout);
    cin.tie(0)->sync_with_stdio(0);
    cout.tie(0);
    cin >> n >> q;
    for(int i = 1;i <= n; ++i){
        int x;
        cin >> x;
        update(i , x);
    }
    while(q--){
        int op , a , b;
        cin >> op;
        if(op == 0){
            cin >> a >> b;
            update(a,b);
        }
        else if(op == 1){
                cin >> a >> b;
                cout << sum(b) - sum(a - 1) << "\n";
             }else{
                cin >> a;
                cout << caut(a) << "\n";
             }
    }
}