Cod sursa(job #539240)

Utilizator mottyMatei-Dan Epure motty Data 22 februarie 2011 18:33:37
Problema Arbori indexati binar Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include <fstream>

using namespace std;

#define length(x) ((-x) & (x))

const int MAX_N = 100005;

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

int n, m;
int aib[MAX_N];

void Read()
{
    in >> n >> m;

    for (int i = 1; i <= n; ++i)
    {
        int actValue;

        in >> actValue;

        //Initialize AIB
        aib[i] += actValue;
        if (i + length(i) <= n)
        {
            aib[ i + length(i) ] += aib[i];
        }
    }
}

void Update(int poz, int value)
{
    while (poz <= n)
    {
        aib[poz] += value;
        poz += length(poz);
    }
}

int Query(int poz)
{
    int sum=0;

    while(poz)
    {
        sum += aib[poz];
        poz -= length(poz);
    }

    return sum;
}

int GetLowestPosition(int value)
{
    int pos = 0, add = 1;

    for (add = 1; add << 1 <= n; add <<= 1);

    while(add)
    {
        if (pos + add <= n && aib[pos + add] <= value)   // daca zice wefgef...
        {
            value -= aib[pos + add];
            pos += add;
        }
        add >>= 1;
    }

    return value ? -1 : pos;
}

void AnswerQueries()
{
    while(m--)
    {
        int type;
        in >> type;

        if(type==0)
        {
            int poz, value;
            in >> poz >> value;

            Update( poz, value);
        }
        else if(type==1)
        {
            int begin, end;
            in >> begin >> end;

            out << Query(end) - Query(begin-1) << '\n';
        }
        else
        {
            int value;
            in >> value;

            out << GetLowestPosition(value) << '\n';
        }
    }
}

int main()
{
    Read();
    AnswerQueries();

    return 0;
}