Cod sursa(job #1329642)

Utilizator radarobertRada Robert Gabriel radarobert Data 29 ianuarie 2015 18:49:54
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include <cstdio>

using namespace std;

int n;
int c[100002];

void add (int ind, int val)
{
    int poz = 0;
    while (ind <= n)
    {
        c[ind] += val;
        while ((ind & 1<<poz) == 0)
            ++poz;
        ind += 1<<poz;
        ++poz;
    }
}

int sum (int ind)
{
   int result = 0;
   int pos = 0;
   while (ind > 0)
   {
       result += c[ind];
       while ((ind & 1<<pos) == 0)
           ++pos;
        ind -= 1<<pos;
        ++pos;
   }
   return result;
}

int t2(int val)
{
    int step, j;
    for (step = 1; step < n; step <<= 1);

    for (j = 0; step; step >>= 1)
    {
        if (j + step <= n)
        {
            if (c[j+step] <= val)
            {
                val -= c[j+step];
                j += step;
                if (!val)
                {
                    return j;
                }
            }
        }
    }
    return -1;
}

int main()
{
    FILE *in = fopen("aib.in", "r");
    FILE *out = fopen("aib.out", "w");

    int m;
    fscanf(in, "%d%d", &n, &m);

    for (int x, i = 1; i <= n; ++i)
    {
        fscanf(in, "%d", &x);
        add(i, x);
    }

    int a, b, t;
    for (int i = 1; i <= m; ++i)
    {
        fscanf(in, "%d%d", &t, &a);
        if (t == 0)
        {
            fscanf(in, "%d", &b);
            add(a, b);
        }
        if (t == 1)
        {
            fscanf(in, "%d", &b);
            int result = sum(b) - sum(a-1);
            fprintf(out, "%d\n", result);
        }
        if (t == 2)
        {
            fprintf(out, "%d\n", t2(a));
        }
    }

    return 0;
}