Cod sursa(job #750067)

Utilizator Theorytheo .c Theory Data 20 mai 2012 14:55:26
Problema Arbori indexati binar Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 2.37 kb
#include<fstream>
#define nmax 100005
using namespace std;
ifstream fin("aib.in");
ofstream fout("aib.out");
int n, m, v[nmax], c[2 * nmax];
void display()
{

    for(int i = 1; i <= n; i++)
        fout <<c[i] <<" ";
    fout <<'\n';

}
void build()
{
    int val = 0, Nr = 0;
    bool ok;
    for(int i = 1; i <= n; ++i)
    {
        v[i] = v[i - 1] + v[i];//suma partiala
       // fout << v[i] <<" ";
    }
    for(int i = 1; i <= n; ++i)
    {
        val = 1  ; Nr = 0;
        while((i & val ) == false )// vedem cate zerouri are indicele curent
        {
            Nr++;
            val *= 2;
        }
        c[i] = v[i] - v[i - val ];//c[i] = sum(i - 2^Nr, i);

    }
}
void add(int poz, int val)
{
    int i, Nr, val2;
    Nr = 0;

    while(poz <= n )
    {
        c[poz] += val;

        while( (poz & (1<<Nr) )==0 ) Nr++;

        poz+= (1<<Nr); Nr++;//nr de zerouri nu trebuie resetat, tot timpul va fi mai mare
    }

}
int sum(int st, int dr)
{
    int i, val = 1, poz, S = 0;
    st--;
    while(dr)
    {
        S+= c[dr];
        while((dr & val )==0)
            val*=2;
        dr -= val;
    }
    val = 1;
    while(st)
    {
        S-= c[st];
        while((st & val) == 0)
            val *= 2;
        st -= val;

    }
    return S;
}
int begin (int S)
{

    int step, i;
    for(step = 1; step <= n; step <<=1);

    for(i = 0; step ; step >>= 1)
       {
           if(i + step <= n && S >= c[i+ step])
           {
               i += step;
               S -= c[i];
               if(!S)
                return i;
           }
       }
    return -1;
}
void read()
{
    int poz, val, st, dr, S;
    fin >> n >> m;
    for(int i = 1; i <= n; i++)
        fin >>v[i];
    build();//construim structura arborescenta cu valorile initiale
    for(int i = 1; i <= m; i++)
    {
        int s;
        fin>>s;
        if(s == 0)
        {
            fin >>poz >>val;
            add(poz, val); //adaugam elemntului poz, val
        }
        if(s == 1)
        {
            fin >> st >>dr;
            fout <<  sum(st, dr) <<'\n';
        }
        if(s == 2)
        {
            fin >> S;
            fout << begin(S) <<'\n';
        }
    }


}
int main()
{
    read();
//    bool ok;
//    ok = 16 & 16;
//    fout <<ok;
    fin.close();
    return 0;
}