Cod sursa(job #1575163)

Utilizator CostanMiriamCostan Miriam CostanMiriam Data 21 ianuarie 2016 10:35:04
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include <fstream>

#define DIM 100010

using namespace std;

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

int n, m;

int AIB[DIM];

inline int lsb (const int &i) {
    return i & (-i);
}

void update (int poz, int x) {

    for (int i = poz; i <= n; i += lsb(i))
        AIB[i] += x;

}

int query (int poz) {

    int sum = 0;

    for (int i = poz; i >= 1;i -= lsb(i))
        sum += AIB[i];

    return sum;

}

int Search(int val) {

    int pow, sum = 0, i = 0;

    for (pow = 0; (1 << pow) < n; pow++);

    for(pow; pow >= 0; pow--) {

        if(i + (1 << pow) > n)
            continue;

        if(sum + AIB[i + (1 << pow)] < val) {

            sum += AIB[i + (1 << pow)];

            i += (1 << pow);

        }

    }

    return (query(i + 1) == val ? i + 1 : -1);

}

int main() {

    fin >> n >> m;

    for(int i = 1; i <= n; i++) {

        int x;

        fin >> x;

        update(i, x);

    }

    while(m--) {

        int op;

        fin >> op;

        if(op == 0) {

            int x, y;

            fin >> x >> y;

            update(x, y);

            continue;

        }

        if(op == 1) {

            int x, y;

            fin >> x >> y;

            fout << query(y) - query(x - 1)<< "\n";

            continue;

        }

        int x;

        fin >> x;

        fout << Search(x) << "\n";

    }

    return 0;

}

//Miriam e are!