Cod sursa(job #2249626)

Utilizator NashikAndrei Feodorov Nashik Data 30 septembrie 2018 09:38:48
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include <cstdio>
#include <vector>
 
using namespace std;
 
vector<int> arb;
 
int Query(int);
 
void Update(int poz, int val)
{
    int C = 0;
    while(poz<arb.size())
    {
        arb[poz] += val;
        while (!(poz &(1<<C)))
               C++;
        poz = poz + (1<<C);
        C= C+1;
    }
}
 
 
int Query(int poz)
{
    int C = 0, S = 0;
 
    while(poz>0)
    {
        S += arb[poz];
        while (!(poz &(1<<C)))
               C++;
        poz = poz - (1<<C);
        C= C+1;
    }
    return S;
}
 
int Search(int val)
{
    int i, step;
    for (step = 1; step < arb.size()-1; step = step * 2);
 
    for (i=0; step > 0; step = step / 2)
        if(i + step <= arb.size()-1)
            if( val >= arb[i+step])
            {
                i = i + step;
                val = val - arb[i];
                if(!val)
                    return i;
            }
 
    return -1;
}
 
 
int main()
{
    freopen("aib.in", "r", stdin);
    freopen("aib.out", "w", stdout);
 
    int n, m, i, j, x, y;
 
    scanf("%d%d", &n, &m);
    arb.assign(n+1, 0);
 
    for(i=1; i<=n; ++i)
    {
        scanf("%d", &x);
        Update(i, x);
    }
 
    for(i=0; i<m; ++i)
    {
        scanf("%d", &x);
        if (x == 0)
        {
            scanf("%d%d", &x, &y);
            Update(x, y);
        }
        else if (x == 1)
        {
            scanf("%d%d", &x, &y);
            printf("%d\n", Query(y) - Query(x-1));
        }
        else if (x == 2)
        {
            scanf("%d", &x);
            printf("%d\n", Search(x));
        }
    }
 
    return 0;
}