Cod sursa(job #1093514)

Utilizator Theorytheo .c Theory Data 28 ianuarie 2014 08:44:15
Problema Arbori indexati binar Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 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 int 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;
    }
    int64_t sum(int pos) {


        int64_t S = 0;

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

    int BinarySearch(int64_t A) {

        int pos; int step;

        step = (1 << 20);

        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; int64_t 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;
}