Cod sursa(job #1093498)

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

using namespace std;

#define int64 long long
#define get(X) (X & (X ^ (X - 1)))

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

int N; int M;

class BinaryIndexedTree {

    public:

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


    void add(int pos, int64 value) {

        for(; pos <= N ; pos += get(pos))
            Aib[pos] += value;
    }

    int64 sum(int pos) {

        int64 S = 0;

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

    int BinarySearch(int64 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){

        int pos; int64 value;
        fin >> value ;

        Bit.add(i, value);
    }

    while(M--) {
        int type; int64 A; int pos; int 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;
}