Cod sursa(job #1685352)

Utilizator cristinamateiCristina Matei cristinamatei Data 11 aprilie 2016 17:07:13
Problema Arbori indexati binar Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int N = 100006;
int n, m, aib[N];

int interogare( int p )
{
    int s = 0;
    while( p != 0 )
    {
        s+=aib[p];
        p-=p&(-p);
    }
    return s;
}

void actualizare( int p, int val )
{
    while( p <= n )
    {
        aib[p]+=val;
        p+=p&(-p);
    }
}

void caut( long long x )
{
    int i = 0;
    unsigned long long pas = 1<<30;
    //cout << pas;
    while( pas != 0 )
    {
        if ( i + pas <= n && aib[i+pas] <= x )
        {
            x-=aib[i+pas];
            i+=pas;
            /*if ( x == 0 )
            {
                out <<i<<'\n';
                return;
            }*/
        }
        pas/=2;
    }
    if ( x == 0 )
        out <<i<<'\n';
    else out <<-1<<'\n';
}

int main()
{
    int i, y, t;
    long long s, x;
    in >> n >> m;
    for ( i = 1; i <= n; i++ )
    {
        in >> x;
        actualizare(i, x);
    }
    for ( i = 1; i <= m; i++ )
    {
        in >> t;
        if ( t == 0 )
        {
            in >> x >> y;
            actualizare(x, y);
        }
        if ( t == 1 )
        {
            in >> x >> y;
            s = interogare(y) - interogare(x-1);
            out << s <<'\n';
        }
        if ( t == 2 )
        {
            in >> x;
            caut(x);
        }
    }
    return 0;
}