Cod sursa(job #1479665)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 31 august 2015 20:22:09
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.17 kb
#include <bits/stdc++.h>

using namespace std;

template <const size_t MAX_SIZE>
class BinaryIndexedTree ///1-based
{
private:

    int bit[MAX_SIZE + 1];

    int lsb(int x) const
    {
        return x & (-x);
    }

    int query(size_t position) const
    {
        int sum = 0;

        while (position > 0)
        {
            sum += bit[position];
            position -= lsb(position);
        }

        return sum;
    }

public:

    BinaryIndexedTree() {
    }

    void update(size_t position, const int value)
    {
        assert(1 <= position);
        assert(position <= MAX_SIZE);

        while (position <= MAX_SIZE)
        {
            bit[position] += value;
            position += lsb(position);
        }
    }

    int query(size_t start, size_t finish) const
    {
        assert(1 <= start);
        assert(start <= finish);
        assert(finish <= MAX_SIZE);

        return query(finish) - query(start - 1);
    }

    int binary_search(const int sum) const
    {
        size_t step = 1;
        int tmpSum = sum;
        size_t position = 0;

        while (step < MAX_SIZE)
            step <<= 1;

        while (step > 0)
        {
            if (position + step <= MAX_SIZE)
            {
                if (bit[position + step] < tmpSum)
                {
                    tmpSum -= bit[position + step];
                    position += step;
                }
            }

            step >>= 1;
        }

        if (query(position + 1) == sum)
            return position + 1;
        else
            return -1;
    }
};

BinaryIndexedTree<100000> BIT;

int main()
{
    ifstream in("aib.in");
    ofstream out("aib.out");

    int N, Q;
    in >> N >> Q;

    for (int i = 1; i <= N; ++i)
    {
        int x;
        in >> x;

        BIT.update(i, x);
    }

    while (Q--)
    {
        int tip, a, b;

        in >> tip;

        if (tip == 0)
        {
            in >> a >> b;
            BIT.update(a, b);
        }
        else if (tip == 1)
        {
            in >> a >> b;
            out << BIT.query(a, b) << "\n";
        }
        else
        {
            in >> a;
            out << BIT.binary_search(a) << "\n";
        }
    }

    return 0;
}