Cod sursa(job #2735451)

Utilizator Iulia25Hosu Iulia Iulia25 Data 2 aprilie 2021 13:48:19
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <fstream>

using namespace std;

ifstream cin ("aib.in");
ofstream cout ("aib.out");

int n, m, N = 1;
int aib[100005];

int lsb(int x)  {
    return (x & (-x));
}

void Update(int nod, int val)    { //nodul si valoarea pe care o adaug
    while (nod <= N) {
        aib[nod] += val;
        nod += lsb(nod);
    }
}

int Query(int nod)  {
    int ans = 0;
    while (nod > 0) {
        ans += aib[nod];
        nod -= lsb(nod);
    }
    return ans;
}

int bs(int val, int nod) {
    int new_nod = nod - lsb(nod);
    for (int x = nod / 2; x >= 0; x >>= 1)    {
        new_nod += x;
        if (aib[new_nod] == val)
            return new_nod;
        if (aib[new_nod] > val)
            return bs(val, new_nod - (x >> 1));
    }
    return -1;
}

int main()  {
    cin >> n >> m;
    while (N < n)
        N <<= 1;
    int type, x, y;
    for (int i = 1; i <= n; ++i)    {
        cin >> x;
        Update(i, x);
    }
    while (m--) {
        cin >> type;
        if (type == 0)  {
            cin >> x >> y;
            Update(x, y);
        }
        if (type == 1)  {
            cin >> x >> y;
            cout << Query(y) - Query(x - 1) << '\n';
        }
        if (type == 2)  {
            cin >> x;
            if (aib[n] == x)
                cout << n << '\n';
            else
                cout << bs(x, N) << '\n';
        }
    }
    return 0;
}