Cod sursa(job #2919392)

Utilizator Alex_HossuHossu Alexandru Alex_Hossu Data 17 august 2022 12:01:34
Problema Arbori indexati binar Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <fstream>

#define MAXN 100005

int aib[MAXN];

int query(int pos) {
  int ans = 0;
  while (pos) {
    ans += aib[pos];
    pos -= pos & (-pos);
  }
  return ans;
}

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

inline int interval(int pos1, int pos2) {
  return query(pos2) - query(pos1 - 1);
}

int main() {
  std::ifstream fin("aib.in");
  std::ofstream fout("aib.out");
  int nrn, nrm, num, type, pos;
  int pos1, pos2;
  fin >> nrn >> nrm;
  for (int index = 1; index <= nrn; index++) {
    fin >> num;
    update(index, num, nrn);
  }
  for (int index = 0; index < nrm; index++) {
    fin >> type;
    if (type == 0) {
      // Update
      fin >> pos >> num;
      update(pos, num, nrn);
    } else if (type == 1) {
      // Query 1
      fin >> pos1 >> pos2;
      fout << interval(pos1, pos2) << std::endl;
    } else {
      // Query 2
      fin >> num;
      pos1 = 1;
      pos2 = nrn + 1;
      while (pos2 - pos1 > 1) {
        int mij = (pos1 + pos2) / 2;
        if (query(mij) <= num)
          pos1 = mij;
        else
          pos2 = mij;
      }
      if (query(pos1) == num)
        fout << pos1 << std::endl;
      else
        fout << -1 << std::endl;
    }
  }
}