Cod sursa(job #3155827)

Utilizator vlad_dimuVlad Dimulescu vlad_dimu Data 9 octombrie 2023 20:17:02
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <bits/stdc++.h>
#define MAXN 100000
using namespace std;

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

int v[MAXN + 1];
int aib[MAXN + 1];
int n;

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

void build(){
  for( int i = 1; i <= n; i++ ){
    aib[i] += v[i];
    if( i + lsb(i) <= n )
      aib[i + lsb(i)] += aib[i];
  }
}

void update( int poz, int val ){
  while( poz <= n )
    aib[poz] += val, poz += lsb(poz);
}

int suma( int poz ){
  int S = 0;
  while( poz > 0 )
    S += aib[poz], poz -= lsb(poz);

  return S;
}

int Search( int val ){
  int i, pas;
  pas = 1;
  while( pas < n ) pas *= 2;

  for( i = 0; pas > 0; pas /= 2 ){
    if( i + pas <= n ){
      if( val >= aib[i + pas] ){
        i += pas, val -= aib[i];
        if( !val ) return i;
      }
    }
  }
  return -1;
}

int main(){
  int m, i, op, poz, val, k, a, b;
  fin >> n >> m;

  for( i = 1; i <= n; i++ )
    fin >> v[i];

  build();
  for( i = 1; i <= m; i++ ){
    fin >> op;
    if( op == 0 )
      fin >> poz >> val, update( poz, val );
    else if( op == 1 ){
      fin >> a >> b;
      fout << suma(b) - suma(a - 1) << '\n';
    }
    else{
      fin >> k;
      fout << Search(k) << '\n';
    }
  }
}