Cod sursa(job #1151868)

Utilizator OwlreeRobert Badea Owlree Data 24 martie 2014 13:33:00
Problema Arbori indexati binar Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.38 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

class Bit
{
private:
    int size;
    int* tree;
public:
    Bit(int size);
    void putValue(int value, int index);
    int getCumulative(int index);
    int getInterval(int start, int end);
    int searchIndex(int cumulative);
};

int main(int argc, const char * argv[])
{
    ifstream in("aib.in");
    ofstream out("aib.out");
    
    int N, M;
    in >> N >> M;
    
    Bit bit(N);
    
    for (int i = 1; i <= N; ++i)
    {
        int val;
        in >> val;
        bit.putValue(val, i);
    }
    
    for (int i = 0; i < M; ++i)
    {
        int op;
        in >> op;
        
        if (op == 0)
        {
            int index;
            int value;
            in >> index >> value;
            bit.putValue(value, index);

        }
        else if (op == 1)
        {
            int a, b;
            in >> a >> b;
            out << bit.getInterval(a, b) << "\n";
        }
        else if (op == 2)
        {
            int cumulative;
            in >> cumulative;
            out << bit.searchIndex(cumulative) << "\n";
        }
    }
    
    in.close();
    out.close();
    
    return 0;
}

Bit::Bit(int size)
{
    this->size = size;
    this->tree = new int[size + 1];
    for (int i = 0; i < size + 1; ++i)
    {
        this->tree[i] = 0;
    }
}

int Bit::getCumulative(int index)
{
    int sum = this->tree[0];
    while (index > 0)
    {
        sum += this->tree[index];
        index &= index - 1;
    }
    return sum;
}

void Bit::putValue(int value, int index)
{
    while (index <= this->size)
    {
        this->tree[index] += value;
        index = index + (index & (-index));
    }
    
}

int Bit::getInterval(int start, int end)
{
    int a = this->getCumulative(start - 1);
    int b = this->getCumulative(end);
    return b - a;
}

int Bit::searchIndex(int cumulative)
{
    int index = 0;
    int bitMask = 1;
    for (bitMask = 1; bitMask <= this->size; bitMask <<= 1);
    bitMask /= 2;
    
    if (cumulative > this->tree[0])
    {
        while (bitMask != 0)
        {
            int textIndex = index + bitMask;
            if (cumulative >= this->tree[index + bitMask])
            {
                index = textIndex;
                cumulative -= this->tree[index];
                if (cumulative == 0) return index;
            }
            bitMask /= 2;
        }
    }
    
    return -1;
}