Cod sursa(job #2030215)

Utilizator PondorastiAlex Turcanu Pondorasti Data 1 octombrie 2017 12:16:00
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#include <fstream>
using namespace std;
const int NMAX = 1e5;
int n, m, aib[NMAX + 2], a, b, q;
int lastBit(int x) { return x & (-x);}
void update(int poz, int val, int n) {
    for(; poz <= n; poz += lastBit(poz))
        aib[poz] += val;
}
int query(int poz) {
    int ans = 0;
    for(; poz; poz -= lastBit(poz))
        ans += aib[poz];
    return ans;
}
int cautBin(int st, int dr, int val) {
    int last = 0;
    while(st <= dr) {
        int med = (st + dr) / 2;
        if(query(med) < val) {
            last = med;
            st = med + 1;
        } else {
            dr = med - 1;
        }
    }
    if(query(last + 1) == val)
        return last + 1;
    return -1;
}
int main() {
    ifstream cin("aib.in");
    ofstream cout("aib.out");
    cin >> n >> m;
    for(int i = 1; i <= n; ++i) {
        cin >> a;
        update(i, a, n);
    }
    for(int i = 1; i <= m; ++i) {
        cin >> q;
        if(q == 2) {
            cin >> a;
            cout << cautBin(1, n, a) << "\n";
        } else {
            cin >> a >> b;
            if(q == 0) {
                update(a, b, n);
            } else {
                cout << query(b) - query(a - 1) << "\n";
            }
        }
        
    }
}