Cod sursa(job #2176327)

Utilizator razvan99hHorhat Razvan razvan99h Data 16 martie 2018 22:48:01
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.65 kb
#include <iostream>
#include <fstream>
#define DM 100005
using namespace std;
ifstream fin("aib.in");
ofstream fout("aib.out");

int aib[DM], n, m, x, a, b;

void update(int pos, int val)
{
    for(; pos <= n; pos += (pos & (-pos)))
        aib[pos] += val;
}
int sum(int pos)
{
    int rez = 0;
    for(; pos > 0; pos -= (pos & (-pos)))
        rez += aib[pos];
    return rez;
}
int query(int a, int b)
{
    return (sum(b) - sum(a - 1));
}
int caut_bin(int val) // O(log^2 n)
{
    int st = 0, dr = n + 1, mij;
    while(dr - st > 1)
    {
        int mij = (st + dr) / 2;
        if(val > sum(mij))
            st = mij;
        else dr = mij;
    }
    if(sum(dr) == val)
        return dr;
    return -1;
}

int caut_bin_Patrascu(int val) // O(log n) - dubioasa
{
    int pos = 0, step = 1, aux = val;
    for(; step <= n; step <<= 1) ;
    for(; step > 0; step >>= 1)
        if(pos + step <= n)
            if(aib[pos + step] < val)
            {
                pos += step;
                val -= aib[pos];
            }
    pos++;
    if(sum(pos) == aux)
        return pos;
    return -1;
}

int main()
{
    fin >> n >> m;
    for(int i = 1; i <= n; i++)
    {
        fin >> x;
        update(i, x);
    }
    for(int i = 1; i <= m; i++)
    {
        fin >> x;
        if(x == 0)
        {
            fin >> a >> b;
            update(a, b);
        }
        if(x == 1)
        {
            fin >> a >> b;
            fout << query(a, b) << '\n';
        }
        if(x == 2)
        {
            fin >> a;
            fout << caut_bin_Patrascu(a) << '\n';
        }
    }
    return 0;
}