Cod sursa(job #1692187)

Utilizator Vlad_317Vlad Panait Vlad_317 Data 20 aprilie 2016 13:13:46
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
#include <stdio.h>

using namespace std;

const int MAX = 100001;

int aib[MAX];
int n, m;

int ub(int x)
{
    return x & (-x);
}

void update(int poz, int val)
{
    if(poz > n)
        return;
    aib[poz] += val;
    poz += ub(poz);
    update(poz, val);
}

int query(int poz)
{
    int s = 0;
    while(poz)
    {
        s += aib[poz];
        poz -= ub(poz);
    }
    return s;
}

int search(int val)
{
    int pas, i = 0;
    for(pas = 1; pas < n; pas <<= 1);

    while(pas)
    {
        if(i + pas <= n)
            if(val >= aib[i + pas])
        {
            i += pas;
            val -= aib[i];
            if(!val)
                return i;
        }
        pas >>= 1;
    }
    return -1;
}




int main()
{
    FILE *fin, *fout;

    fin = fopen("aib.in", "r");
    fout = fopen("aib.out", "w");

    fscanf(fin, "%d%d", &n, &m);

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

    for(int i = 1; i <= m; i++)
    {
        int op;
        fscanf(fin, "%d", &op);
        if(op == 0)
        {
            int a, b;
            fscanf(fin, "%d%d", &a, &b);
            update(a, b);
        }
        if(op == 1)
        {
            int a, b;
            fscanf(fin, "%d%d", &a, &b);
            fprintf(fout, "%d\n", query(b) - query(a - 1));
        }
        if(op == 2)
        {
            int a;
            fscanf(fin, "%d", &a);
            fprintf(fout, "%d\n", search(a));
        }
    }



    return 0;
}