Cod sursa(job #2750633)

Utilizator justin.stoicaJustin Stoica justin.stoica Data 12 mai 2021 17:11:02
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <fstream>

using namespace std;
int aib[100005];
int query(int pos)
{
    int s = 0;
    while(pos>0)
    {
        s = s + aib[pos];
        pos = pos & (pos - 1);
    }
    return s;
}

void update(int pos,int val,int n)
{
    while(pos <= n)
    {
        aib[pos] = aib[pos] + val;
        pos = pos + (pos ^ (pos & (pos - 1)));
    }
}

int main()
{
    ifstream cin("aib.in");
    ofstream cout("aib.out");
    int n, m;
    cin >> n >> m;
    for(int i = 1; i <= n; i ++)
    {
        int x;
        cin >> x;
        update(i, x, n);
    }
    for(int i = 0; i < m; i ++)
    {
        int cer,a, b;
        cin >> cer >> a;
        if(cer == 0)
        {
            cin >> b;
            update(a, b, n);
        }
        else if(cer == 1)
        {
            cin >> b;
            cout << query(b) - query(a - 1) << endl;
        }
        else
        {
            int st,dr,med,last,curr;
            st = 1;
            dr = n;
            last = -1;
            while(st <= dr)
            {
                med = ((st + dr) / 2);
                curr = query(med);
                if(curr == a){
                    last = med;
                    dr = med - 1;
                }
                else if(curr > a)
                    dr = med - 1;
                else
                    st = med + 1;
            }
            if(last == -1)
                cout << "-1" << '\n';
            else
                cout << last << '\n';
        }
    }
    return 0;
}