Cod sursa(job #2735465)

Utilizator Iulia25Hosu Iulia Iulia25 Data 2 aprilie 2021 14:02:20
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 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 ans = 0, sum = 0;
    for (int bit = 16; bit >= 0; --bit) {
        if (ans + (1 << bit) <= n && sum + aib[ans + (1 << bit)] <= val) {
            ans += (1 << bit);
            sum += aib[ans];
        }
    }
    if (sum == val && ans)
        return ans;
    return -1;
}

int main()  {
    cin >> n >> m;
    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;
            cout << bs(x) << '\n';
        }
    }
    return 0;
}