Cod sursa(job #2818476)

Utilizator vladburacBurac Vlad vladburac Data 16 decembrie 2021 09:57:09
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <iostream>
using namespace std;
const int MAXN = 1e5;

int aib[MAXN+1];
int n, maxp2;

void update( int pos, int val ) {
  while( pos <= n ) {
    aib[pos] += val;
    pos += pos & ( -pos );
  }
}

int calcSum( int pos ) {
  int sum = 0;
  while( pos > 0 ) {
    sum += aib[pos];
    pos -= pos & ( -pos );
  }
  return sum;
}

int Search( int value ) {
  int pos, sum, step;
  step = maxp2;
  pos = sum = 0;
  while( step ) {
    if( pos + step <= n && sum + aib[pos+step] <= value ) {
      sum += aib[pos+step];
      pos += step;
    }
    step /= 2;
  }
  return pos;
}

int main() {
  FILE *fin, *fout;
  int m, i, a, b, op;
  fin = fopen( "aib.in", "r" );
  fout = fopen( "aib.out", "w" );
  fscanf( fin, "%d%d", &n, &m );
  for( i = 1; i <= n; i++ ) {
    fscanf( fin, "%d", &a );
    update( i, a );
  }
  maxp2 = 1;
  while( maxp2 * 2 <= n ) {
    maxp2 *= 2;
  }
  for( i = 1; i <= m; i++ ) {
    fscanf( fin, "%d", &op );
    switch ( op ){
    case 0:
      fscanf( fin, "%d%d", &a, &b );
      update( a, b );
      break;
    case 1:
      fscanf( fin, "%d%d", &a, &b );
      fprintf( fout, "%d\n", calcSum(b) - calcSum(a-1) );
      break;
    default:
      fscanf( fin, "%d", &a );
      fprintf( fout, "%d\n", Search(a) );
    }
  }
  fclose( fin );
  fclose( fout );
  return 0;
}