Cod sursa(job #2430715)

Utilizator Rufus007Marincia Catalin Rufus007 Data 15 iunie 2019 22:40:06
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include<fstream>
std::ifstream fin("cautbin.in");
std::ofstream fout("cautbin.out");
const int NMAX = 100011;
int sir[NMAX];

int oper_0(int a[], int dim, int value) {
  int step, i;
  for (step = 1; step < dim; step <<= 1);

  for (i = 0; step; step >>= 1)
    if (i + step < dim && a[i + step] <= value)
      i += step;

  if (a[i] != value || i > dim - 1)
    return -1;
  else
    return i + 1;
}

int oper_1(int a[], int dim, int value) {
  int step, i;
  for (step = 1; step < dim; step <<= 1);

  for (i = 0; step; step >>= 1)
    if (i + step < dim && a[i + step] <= value)
      i += step;
  return i + 1;
}
int oper_2(int a[], int dim, int value) {
  int step, i;
  for (step = 1; step < dim; step <<= 1);

  for (i = 0; step; step >>= 1)
    if (i + step < dim && a[i + step] <= value - 1)
      i += step;

  if (i == 0 && a[i] >= value)
    return 1;
  else
    return i + 2;
}

int main() {
  int N, M, operatie, x;

  fin >> N;
  for (int i = 0; i < N; ++i)
    fin >> sir[i];
  fin >> M;
  for (int i = 0; i < M; ++i) {
    fin >> operatie >> x;

    switch (operatie) {
      case 0:fout << oper_0(sir, N, x) << "\n";
        break;

      case 1:fout << oper_1(sir, N, x) << "\n";
        break;
      case 2:fout << oper_2(sir, N, x) << "\n";
        break;
      default:break;
    }
  }

  fin.close();
  fout.close();
  return 0;
}