Cod sursa(job #1905551)

Utilizator tudorgalatanRoman Tudor tudorgalatan Data 6 martie 2017 09:16:02
Problema Arbori indexati binar Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
#include <fstream>

using namespace std;

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

inline void ADD (unsigned int pos, unsigned int val);
inline unsigned int SUM (unsigned int pos);
int BIN_SRC (unsigned int val);

unsigned int N , M;
unsigned int A;
unsigned int type;
unsigned int a, b;

unsigned int BIT[100001];    /// BIT = Binary Indexed Tree
unsigned int i;

int main ()
{
    fin >> N >> M;
    for (i=1; i<=N; i++)
    {
        fin >> type;
        if (type == 0)
        {
            fin >> a >> b;
            ADD(a,b);
        }
        else
            if (type == 1)
            {
                fin >> a >> b;
                fout << SUM(b) - SUM(a-1) << '\n';
            }
            else
            {
                fin >> a;
                fout << BIN_SRC(a) << '\n';
            }
    }
    return 0;
}

inline void ADD (unsigned int pos, unsigned int val)
{
    while (pos <= N)
    {
        BIT[pos] += val;
        pos = (pos^(pos-1))&pos;
    }
}

inline unsigned int SUM (unsigned int pos)
{
    unsigned int sum;
    sum = 0;
    while (pos > 0)
    {
        sum += BIT[pos];
        pos -= (pos^(pos-1))&pos;
    }
    return sum;
}

int BIN_SRC (unsigned int val)
{
    unsigned int i, k;
    i = 0;
    k = 1;
    while (k < N)
        k *= 2;
    while (k > 0)
    {
        if (i+k <= N)
            if (SUM(i+k) == val)
                return i+k;
            else
                if (SUM(i+k) < val)
                    i += k;
        k /= 2;
    }
    return -1;
}