Cod sursa(job #880953)

Utilizator vgabi94Vaduva Gabriel vgabi94 Data 17 februarie 2013 15:53:02
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.81 kb
#include <fstream>
using namespace std;

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

struct AIB {
    AIB(int);
    ~AIB() { delete[] c; }
    void add(int, int);
    int sum(int, int);
    int minPos(int);
private:
    int sumTo(int);  // Suma din interv [1, pos]
    int * c;
    int N;
};
AIB::AIB(int n)
{
    c = new int[n+1]; N = n;
    for (int i = 1; i <= N; i++) c[i] = 0;
}
void AIB::add(int ind, int val)
{
    int poz = 0;
    while (ind <= N)
    {
        c[ind] += val;
        while ( (ind & (1 << poz)) == 0 ) poz += 1;
        ind += (1 << poz);
        poz += 1;
    }
}
int AIB::sumTo(int ind)
{
    int sum = 0, poz = 0;
    while (ind > 0)
    {
        sum += c[ind];
        while ( (ind & (1 << poz)) == 0 ) poz += 1;
        ind -= (1 << poz);
        poz += 1;
    }
    return sum;
}
int AIB::sum(int a, int b)
{
    return sumTo(b) - sumTo(a-1);
}
int AIB::minPos(int a)
{
    int step;
    for (step = 1; step < N; step = (step << 1));
    for (int i = 0; step > 0; step = (step >> 1))
    {
        if (i + step <= N)
        {
            if (a >= c[i+step])
            {
                i += step; a -= c[i];
                if (a == 0) return i;
            }
        }
    }
    return -1;
}

int main()
{
    int n, m, x, y, op;
    in >> n >> m;
    AIB bin(n);
    for (int i = 1; i <= n; i++)
    {
        in >> x;
        bin.add(i, x);
    }
    for (int i = 1; i <= m; i++)
    {
        in >> op;
        switch (op)
        {
            case 0: { in >> x >> y; bin.add(x, y); } break;
            case 1: { in >> x >> y; out << bin.sum(x, y) << '\n'; } break;
            case 2: {
                in >> x;
                out << bin.minPos(x) << '\n';
            } break;
        }
    }
    return 0;
}