Cod sursa(job #3155398)

Utilizator Luca_Miscocilucainfoarena Luca_Miscoci Data 8 octombrie 2023 10:50:25
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <fstream>
#define NMAX 100000
#define LOG 17
using namespace std;

int a[NMAX + 1];
int v[NMAX + 1];
int n, t;

int lsb (int x){

  return x & (-x);
}

void build (){

  for (int i = 1; i <= n; i++){
    a[i] += v[i];

    if (i + lsb(i) <= n)
      a[i + lsb(i)] += a[i];
  }
}

void update (int poz, int val){

  while (poz <= n){
    a[poz] += val;
    poz += lsb(poz);
  }

}

int sum (int poz){
  int s = 0;
  while (poz > 0){
    s += a[poz];
    poz -= lsb(poz);
  }

  return s;
}

int bl (int e){
  int s = 0;
  int poz = 0;
  int flag = 0;
  int pas = 1 << LOG;

  while (pas > 0){
    if (pas + poz <= n && s + a[poz + pas] <= e){
      poz += pas;
      s += a[poz];
      flag = 1;
    }

    pas >>= 1;
  }
  if (flag == 0 || s != e)
    return -1;
  return poz;
}

int main(){

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

  int op, up, a, b;

  fin >> n >> t;
  for (int i = 1; i <= n; i++){
    fin >> v[i];
  }

  build ();
  while (t--){
    fin >> op;
    if (op == 0){
      fin >> a >> b;
      update(a, b);
    }
    else if (op == 1){
      fin >> a >> b;
      fout << sum (b) - sum (a - 1) << "\n";
    }
    else {
      fin >> a;
      fout << bl (a) << "\n";
    }

  }
  return 0;
}