Cod sursa(job #2343086)

Utilizator MaxTeoTeo Oprescu MaxTeo Data 13 februarie 2019 17:56:05
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 kb
#include <bits/stdc++.h>
#define lastBit(x) (x & (-x))
using namespace std;

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

const int MAX = 1e5 + 5;

int n, m;

class AIB
{
    public:

    int tree[MAX], size;

    //initialize an AIB of n elements to 0
    AIB()
    {
        size = n;
    }

    ~AIB()
    {
        delete [] tree;
    }

    //returns sum of the range [1..b]
    int Sum(int x)
    {
        int sum = 0;
        for(; x; x -= lastBit(x))
            sum += tree[x];
        return sum;
    }

    //returns sum of the range [a..b]
    int Sum(int a, int b)
    {
        return Sum(b) - (a == 1 ? 0 : Sum(a - 1));
    }
    //update value of k-th element
    void Update(int idx, int value)
    {
        for(; idx <= size; idx += lastBit(idx))
            tree[idx] += value;
    }
};

int Binary_Search(AIB A, int val)
{
    int j, pas;

    for(pas = 1; pas < n; pas <<= 1);
    for(j = 0; pas; pas >>= 1)
    {
        if(j + pas <= n && A.tree[j + pas] <= val)
        {
            j += pas;
            val -= A.tree[j];
            if(val == 0)
                return j;
        }
    }

    return -1;
}

void Solve(AIB A)
{
    int op, a, b;

    while(m--)
    {
        f >> op;
        switch(op)
        {
            case 0: f >> a >> b;      A.Update(a, b);              break;
            case 1: f >> a >> b; g << A.Sum(a, b) << "\n";         break;
            case 2: f >> a;      g << Binary_Search(A, a) << "\n"; break;
        }
    }
}

int main()
{
    f >> n >> m;

    AIB A;

    int x;
    for(int i = 1; i <= n; ++i)
    {
        f >> x;
        A.Update(i, x);
    }

    Solve(A);
    return 0;
}