Cod sursa(job #3237549)

Utilizator tsg38Tsg Tsg tsg38 Data 9 iulie 2024 21:51:02
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.97 kb
#include <bits/stdc++.h>

using namespace std;

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

const int DIM = 1e5 + 1;

int aib[DIM], n;

void upd( int pos, int val ) {
  for ( ; pos <= n; pos += pos & -pos ) {
	aib[pos] += val;
  }
}
int qry( int pos ) {
  int res = 0;
  for ( ; pos > 0; pos -= pos & -pos ) {
	res += aib[pos];
  }
  return res;
}
int find( int sum ) {
  int pos = 0;
  for ( int i = 17; i >= 0; --i ) {
	if ( pos + (1 << i) <= n && aib[pos + (1 << i)] <= sum ) {
	  pos += (1 << i);
	  sum -= aib[pos];
	  if ( sum == 0 ) return pos;
	}
  }
  return -1;
}

int main() {
  ios_base::sync_with_stdio(0);
  fin.tie(0);
  int q, x, y, tp;

  fin >> n >> q;
  for ( int i = 1; i <= n; ++i ) {
	fin >> x;
	upd(i, x);
  }
  while ( q-- ) {
	fin >> tp >> x;
	if ( tp == 0 ) {
	  fin >> y;
	  upd(x, y);
	} else if ( tp == 1 ) {
	  fin >> y;
	  fout << qry(y) - qry(x - 1) << "\n";
	} else {
	  fout << find(x) << "\n";
	}
  }
  fin.close();
  fout.close();
  return 0;
}