Cod sursa(job #2185457)

Utilizator Athena99Anghel Anca Athena99 Data 24 martie 2018 15:41:16
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#include <fstream>

using namespace std;

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

const int nmax= 100000;

int n, m;
int aib[nmax+1];

int aib_query( int p ) {
    int sol= 0;
    for ( ; p>0; p= (p&(p-1)) ) {
        sol+= aib[p];
    }

    return sol;
}

void aib_update( int p, int x ) {
    for ( ; p<=n; p= p*2-(p&(p-1)) ) {
        aib[p]+= x;
    }
}

int main(  ) {
    fin>>n>>m;
    for ( int i= 1, x; i<=n; ++i ) {
        fin>>x;
        aib_update(i, x);
    }

    for ( int x, y, z; m>0; --m ) {
        fin>>x>>y;

        if ( x==0 ) {
            fin>>z;
            aib_update(y, z);
        } else if ( x==1 ) {
            fin>>z;
            fout<<aib_query(z)-aib_query(y-1)<<"\n";
        } else {
            int sol= 0, aux= y;
            for ( int step= (1<<16); step>0; step/= 2 ) {
                if ( sol+step<=n && aib[sol+step]<y ) {
                    y-= aib[sol+step];
                    sol+= step;
                }
            }

            if ( aib_query(sol+1)==aux ) {
                fout<<sol+1<<"\n";
            } else {
                fout<<"-1\n";
            }
        }
    }

    return 0;
}