Cod sursa(job #2315746)

Utilizator Radu_FilipescuFilipescu Radu Radu_Filipescu Data 10 ianuarie 2019 15:08:22
Problema Arbori indexati binar Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.72 kb
#include <fstream>

using namespace std;

ifstream fin( "aib.in" );
ofstream fout( "aib.out" );

const int NMAX = 100005;

int N, M;
int tree[4 * NMAX];

void Update( int nod, int lf, int rg, int pos, int val )
{
  if( lf == rg )
  {
    tree[nod] += val;

    return;
  }

  int mid = ( lf + rg ) / 2;

  if( pos <= mid ) Update( nod * 2, lf, mid, pos, val );
  else Update( nod * 2 + 1, mid + 1, rg, pos, val );

  tree[nod] = tree[nod * 2] + tree[nod * 2 + 1];
}

int Query( int nod, int lf, int rg, int L, int R )
{
  if( L <= lf && rg <= R ) return tree[nod];

  int mid = ( lf + rg ) / 2;

  int ans = 0;

  if( L <= mid ) ans += Query( nod * 2, lf, mid, L, R );
  if( R  > mid ) ans += Query( nod * 2 + 1, mid + 1, rg, L, R );

  return ans;
}

void Read()
{
  fin >> N >> M;

  int nr;
  for( int i = 1; i <= N; ++i )
  {
    fin >> nr;

    Update( 1, 1, N, i, nr );
  }

  int tip, a, b;

  for( int i = 1; i <= M; ++i )
  {
    fin >> tip;

    if( tip == 0 )
    {
      fin >> a >> b;
      Update( 1, 1, N, a, b );
    }

    if( tip == 1 )
    {
      fin >> a >> b;

      fout << Query( 1, 1, N, a, b ) << '\n';
    }

    if( tip == 2 )
    {
      fin >> a;

      int lf, rg, mid, ans;
      bool found = false;

      lf = 1;
      rg = N;

      while( !found && lf <= rg )
      {
        mid = ( lf + rg ) / 2;

        ans = Query( 1, 1, N, 1, mid );

        if( ans == a ) { found = true;
                         fout << mid << '\n';
                       }
        if( ans > a ) rg = mid - 1;
        if( ans < a ) lf = mid + 1;
      }

      if( !found ) fout << "-1\n";
    }
  }
}

int main()
{
   Read();

    return 0;
}