Cod sursa(job #3359551)

Utilizator RuxandraPro12_Metehau Ruxandra Maria RuxandraPro12_ Data 29 iunie 2026 22:52:46
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin ("aib.in");
ofstream fout ("aib.out");

const int NMAX = 1e5;

int n, m, aib[NMAX + 5];

inline int Minim (int a, int b) {
    if (a < b)
        return a;
    return b;
}

void update (int poz, int val) {
    int cnt = 0;
    while (poz <= n) {
        aib[poz] += val;
        while (!(poz & (1 << cnt)))
            cnt++;
        poz += (1 << cnt);
        cnt += 1;
    }
}

int query (int poz) {
    int cnt = 0, s = 0;
    while (poz > 0) {
        s += aib[poz];
        while (!(poz & (1 << cnt)))
            cnt++;
        poz -= (1 << cnt);
        cnt += 1;
    }
    return s;
}

int cautare (int val) {
    int i, step;
    for (step = 1; step < n; step <<= 1);
    for (i = 0; step; step >>= 1) {
        if (i + step <= n) {
            if (val >= aib[i + step]) {
                i += step;
                val -= aib[i];
                if (!val)
                    return i;
            }
         }
    }
    return -1;
}

int main() {
    fin >> n >> m;
    for (int i = 1; i <= n; i++) {
        int x;
        fin >> x;
        update (i, x);
    }

    while (m--) {
        int tip;
        fin >> tip;
        if (tip <= 1) {
            int x, y;
            fin >> x >> y;
            if (tip == 0)
                update (x, y);
            else
                fout << query (y) - query (x - 1) << "\n";
        }
        else {
            int suma_k;
            fin >> suma_k;
            fout << cautare (suma_k) << "\n";
        }
    }
    return 0;
}