Cod sursa(job #2741103)

Utilizator euyoTukanul euyo Data 15 aprilie 2021 15:14:39
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>

using namespace std;

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

const int MAXN = 100003; 

int aib[MAXN], n;

inline int lsb( const int &x ) {
  return (x & (-x));
}

void update( const int &pos, const int &x ) {
  for ( int i = pos; i <= n; i += lsb( i ) ) {
    aib[i] += x;
  }
}
int sum( const int &x, const int &y ) {
  int res = 0;
  
  for ( int i = y; i > 0; i -= lsb( i ) ) {
	res += aib[i];
  }
  for ( int i = x - 1; i > 0; i -= lsb( i ) ) {
	res -= aib[i];
  }
  return res;
}
int find( int &s ) {
  int step, ind = 0; 
  for ( step = 1; step < n; step <<= 1 );
  for ( ; step > 0; step >>= 1 ) {
    if ( ind + step <= n ) {
      if ( s >= aib[ind + step] ) {
		ind += step;
	    s -= aib[ind];
	    if ( s == 0 ) {
		  return ind;
		}
	  }
	}
  }
  return -1;
}

int main() {
  int q, op, a, b;
  
  fin >> n >> q;
  for ( int i = 1; i <= n; ++i ) {
    fin >> a;
	update( i, a );
  }
  while ( q-- ) {
	fin >> op;
	switch ( op ) {
	case 0:
	  fin >> a >> b;
	  update( a, b );
	  break;
	case 1:
	  fin >> a >> b;
      fout << sum( a, b ) << "\n";
      break;
	case 2:
	  fin >> a;
	  fout << find( a ) << "\n";
	  break;
	}
  }
  fin.close();
  fout.close();
  return 0;
}