Cod sursa(job #1470456)

Utilizator borcanirobertBorcani Robert borcanirobert Data 11 august 2015 12:16:35
Problema Arbori indexati binar Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include <fstream>
using namespace std;

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

const int MAX = 100010;
int a[MAX];
int AIB[MAX];
int N, M;
int x, y;
int type;

void Update( int i, int x );
int Search( int val );
int Query( int poz );
int NZero( int a )
{
    return ( a xor ( a - 1 ) ) & a;
}

int main()
{
    int i;

    fin >> N >> M;
    for ( i = 1; i <= N; i++ )
    {
        fin >> a[i];
        Update(i, a[i]);
    }

    for ( i = 1; i <= M; i++ )
    {
        fin >> type;
        if ( type < 2 )
        {
            fin >> x >> y;
            if ( type == 0 ) Update( x, y );
            else             fout << Query( y ) - Query( x - 1 ) << '\n';
        }
        else
        {
            fin >> x;
            fout << Search( x ) << '\n';
        }
    }

    fin.close();
    fout.close();
    return 0;
}

void Update( int i, int x )
{
    int ind;

    for ( ind = i; ind <= N; ind += NZero(ind) )
        AIB[ind] += x;
}

int Search( int val )
{
    int step, i;

    for ( step = 1; step < N; step <<= 1 );

    for ( i = 0; step; step >>= 1 )
        if ( i + step <= N )
        {
            if ( val >= AIB[step + i] )
            {
                i += step, val -= AIB[i];
                if ( !val )
                    return i;
            }
        }
}

int Query( int poz )
{
    int rez = 0, i;

    for ( i = poz; i > 0; i -= NZero(i) )
        rez += AIB[i];

    return rez;
}