Cod sursa(job #2221858)

Utilizator inquisitorAnders inquisitor Data 16 iulie 2018 00:06:02
Problema Arbori indexati binar Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.96 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 - '0';

    return number;
}

__attribute__((always_inline)) void Update(int position, int value)
{
    for(int index = position; index <= length; index += index & -index)
    {
        BIT[index] += value;
    }
}

__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)
    {
        Update(i, get_int());
    }

    while(operations--)
    {
        switch(get_int())
        {
            case 0: x = get_int();
                    y = get_int();
                    Update(x, y);
                    break;

            case 1: printf("%d\n", Querry(get_int()) - Querry(get_int() - 1));
                    break;

            case 2: printf("%d\n", Search(get_int()));
        }
    }

    return 0;
}