Cod sursa(job #2221865)

Utilizator inquisitorAnders inquisitor Data 16 iulie 2018 00:22:50
Problema Arbori indexati binar Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.83 kb
#include <cstdio>

#define BUFFER_SIZE 1 << 18

char inBuffer[BUFFER_SIZE];

int p = BUFFER_SIZE, length, operations, x, y, BIT[100001];

__attribute__((always_inline)) char get_char()
{
    if(p == BUFFER_SIZE)
    {
        fread(inBuffer, 1, BUFFER_SIZE, stdin);

        p = 0;
    }

    return inBuffer[p++];
}

__attribute__((always_inline)) int get_int()
{
    char c = get_char(); int number = 0;

    for(; c < 48 || c > 57; c = get_char());

    for(; c > 47 && c < 58; c = get_char())

        number = number * 10 + c - 48;

    return number;
}

char outBuffer[1650000]; int q = -1;

__attribute__((always_inline)) void put_int(int x)
{
    if(x == -1)
    {
        outBuffer[++q] = 45;

        outBuffer[++q] = 49;

        outBuffer[++q] = 10;

        return;
    }

    int digits = x > 999999999 ? 11 :
                 x > 99999999  ? 10 :
                 x > 9999999   ? 9  :
                 x > 999999    ? 8  :
                 x > 99999     ? 7  :
                 x > 9999      ? 6  :
                 x > 999       ? 5  :
                 x > 99        ? 4  :
                 x > 9         ? 3  : 2;

    for(int i = digits; --i; x /= 10)
    {
        outBuffer[q + i] = x % 10 + 48;
    }

    outBuffer[q = q + digits] = 10;
}

__attribute__((always_inline)) int Querry(int position)
{
    int sum = 0;

    for(int index = position; index; index -= index & -index)
    {
        sum += BIT[index];
    }

    return sum;
}

__attribute__((always_inline)) int Search(int sum)
{
    int i, step;

    for(step = 1; step <= length; step <<= 1);

    for(i = 0; step; step >>= 1)
    {
         if(i + step <= length && sum >= BIT[i + step])
         {
            i += step;

            sum -= BIT[i];

            if(!sum) return i;
         }
    }

    return -1;
}

int main(){

    freopen("aib.in", "r", stdin);
    freopen("aib.out", "w", stdout);

    length = get_int();

    operations = get_int();

    for(int i = 1; i <= length; ++i)
    {
        x = get_int();

        for(int index = i; index <= length; index += index & -index)
        {
            BIT[index] += x;
        }
    }

    while(operations--)
    {
        switch(get_int())
        {
            case 0: y = get_int();

                    for(int index = get_int(); index <= length; index += index & -index)
                    {
                        BIT[index] += y;
                    }

                    break;

            case 1: x = get_int();

                    y = get_int();

                    put_int(Querry(y) - Querry(x - 1));

                    break;

            case 2: x = get_int();

                    put_int(Search(x));
        }
    }

    fwrite(outBuffer, 1, q, stdout);

    return 0;
}