Cod sursa(job #580321)

Utilizator mottyMatei-Dan Epure motty Data 12 aprilie 2011 22:47:08
Problema Arbori indexati binar Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
#include <fstream>

#define lth(x) ((-x) & (x))

using namespace std;

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

const int N = 100001;

int n, m;
int v[N], aib[N];

inline int len(int x)
{
    return (-x) & (x);
}

void PrintAib()
{
    for (int i = 1; i <= n; ++i)
        out << aib[i] << " ";

    out << "\n\n";
}

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

    for (int i = 1; i <= n; ++i)
    {
        in >> v[i];
        aib[i] += v[i];
        aib[i + len(i)] += aib[i];
//      PrintAib();
    }
}

void Update(int pos, int val)
{
    while (pos <= n)
    {
        aib[pos] += val;
        pos += lth(pos);
    }
}

int Query(int pos)
{
    int result = 0;
    
    while (pos)
    {
        result += aib[pos];
        pos -= lth(pos);
    }

    return result;
}

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

    for (step = 1; step < n; step <<= 1);
    for (i = 0; step; step >>= 1)
        if (i + step <= n && aib[i + step] <= val)
        {
            i += step;
            val -= aib[i];
            if (!val)
                return i;
        }

    return -1;
}

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

        if (type == 0)
        {
            int a, b;
            in >> a >> b;
            Update(a, b);
        }
        else if(type == 1)
        {
            int a, b;
            in >> a >> b;

            out << Query(b) - Query(a - 1) << "\n";
        }
        else
        {
            int a;
            in >> a;

            out << Search(a) << "\n";
        }
    }
}

int main()
{
    Read();
    Solve();

    return 0;
}