Cod sursa(job #2042465)

Utilizator BourucLiviuBouruc Petru Liviu BourucLiviu Data 18 octombrie 2017 17:46:31
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#include <fstream>

#define zeros(x) ((x^(x-1))&x)

using namespace std;

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

int n, v[100005];

inline void adauga(int pos, int x)
{
    while(pos <= n)
    {
        v[pos] += x;
        pos += zeros(pos);
    }
}

inline int suma(int pos)
{
    if(pos == 0) return 0;
    else return v[pos] + suma(pos - zeros(pos));
}

int poz_min(int x)
{
    int st, dr, mij, sum;
    st = 1; dr = n;
    while(st <= dr)
    {
        mij = (st+dr) / 2;
        sum = suma(mij);
        if(sum == x) return mij;
        else if(sum < x) st = mij+1;
        else dr = mij-1;
    }
    return -1;
}

int main()
{
    int m, op, x, y;
    fin >> n >> m;
    for(int i = 1; i <= n; ++i)
    {
        fin >> x;
        adauga(i, x);
    }
    while(m--)
    {
        fin >> op;
        if(op == 0)
        {
            fin >> x >> y;
            adauga(x, y);
        }
        else if(op == 1)
        {
            fin >> x >> y;
            fout << suma(y) - suma(x-1) << '\n';
        }
        else
        {
            fin >> x;
            fout << poz_min(x) << '\n';
        }
    }
    return 0;
}