Cod sursa(job #1093501)

Utilizator Theorytheo .c Theory Data 28 ianuarie 2014 08:30:23
Problema Arbori indexati binar Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
#include <fstream>

using namespace std;

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

int N; int M;

class BinaryIndexedTree {

    private:

    static const int NMAX = 100009;
    unsigned Aib[NMAX];

    unsigned Bit(const int X) { return X & ( X ^ (X - 1) ); }

    public:

    void add(int pos, unsigned value) {

        for(; pos <= N ; pos += Bit(pos))
            Aib[pos] += value;
    }
    unsigned sum(int pos) {


        unsigned S = 0;

        for(; pos > 0 ; pos -= Bit(pos))
                S += Aib[pos];
        return S;
    }

    int BinarySearch(unsigned A) {

        int pos; int step;

        step = (1 << 18);

        for(pos = 0 ; step ; step >>= 1 )
            if(pos + step <= N && sum(pos + step) <= A)
                pos += step;
        return sum(pos) == A ? pos : -1;
    }

} Bit ;


int main() {

    fin >> N >> M;

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

        unsigned value;
        fin >> value ;

        Bit.add(i, value);
    }

    while(M--) {

        int type; unsigned A; int pos, pos2;
        fin >> type ;

        switch(type) {

            case 0: fin >> pos >> A ; Bit.add(pos, A); break;
            case 1: fin >> pos >> pos2; fout <<  Bit.sum(pos2) - Bit.sum(pos - 1) << '\n'; break;
            case 2: fin >> A; fout << Bit.BinarySearch(A) <<'\n'; break;
        }

    }

    return 0;
}