Cod sursa(job #2198336)

Utilizator Anastasia11Susciuc Anastasia Anastasia11 Data 24 aprilie 2018 11:45:31
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.68 kb
#include <fstream>
#define Nmax 100005
#define lsb(x) ( (x ^ (x - 1)) & x )

using namespace std;

ifstream f("aib.in");
ofstream g("aib.out");

int n, m, x, t, y, pwr=1;
int arb[Nmax];

void update(int i, int x)
{
    for (;i<=n; i+=lsb(i))
        arb[i] += x;
}

int query(int i)
{
    int sum=0;
     while(i)
     {
         sum+=arb[i];
          i -= (i&-i);
     }
    return sum;
}

int main()
{

    f >> n >> m;/* 25 42 8 15 1 55 16 67  */ while( pwr < n ) pwr*=2;
     for ( int i = 1 ; i <= n ; i ++ )
      {
          f >> x;
          update(i,x);
      }

      while( m -- )
       {
           f >> t;
            if( t == 0 )
             {
                 f >> x >> y;
                 update(x,y);
             } else
            if( t == 1 )
             {
                 f >> x >> y;
                 g << query(y) - query(x-1) << '\n';
             } else
             {
                 f >> x;
                  int p = pwr, j=0;
                  bool ok=false;


                  for( ; p ; p/=2 )
                   {
                        if ( j + p > n ) continue; //***
                        y=query(j+p);
                        if(x == y)
                        {
                            ok=true;
                            g << j+p << '\n' ;
                            break;
                        }
                        else
                         if ( y < x ) j += p;
                   }
                    y = query(j);
                if (ok == false) g << "-1\n";
             }
       }

   // for ( int i =1  ; i <= Nmax ; i ++ )
      // g << arb[i] << " ";
    return 0;
}