Cod sursa(job #2602789)

Utilizator avtobusAvtobus avtobus Data 17 aprilie 2020 20:52:05
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <stdio.h>
#include <bits/stdc++.h>

#define rep(i, n) for(int i = 0; i < n; i++)

using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
const int INF = 0x3f3f3f3f;

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

const int Nmax = 100555;
int N, M, a[Nmax];

int op0(int val) {
  int i = 0, step = 1;
  while(step < N) { step *= 2; }

  for(; step; step /= 2) { // cea mai mare pozitie se afla x;
    if (i + step >= N) { continue; }
    if (a[i+step] <= val) {
      i += step;
    }
  }
  if (a[i] == val) {
    return i+1;
  } else {
    return -1;
  }
}

int op1(int val) {
  int i = 0, step = 1;
  while(step < N) { step *= 2; }
  for(; step; step /= 2) {
    if (i + step >= N) { continue; }
    if (a[i+step] <= val) { // [i, i+step-1]; [i+step, i+]
      i += step;
    }
  }
  return i + 1;
}

int op2(int val) {
  int i = 0, step = 1;
  while(step < N) { step *= 2; }
  for(; step; step /= 2) {
    if (i+step-1 >= N) { continue; }
    if (a[i+step-1] < val) {
      i += step;
    }
  }
  return i+1;
}

int main(void) {
  // freopen("cautbin.in", "r", stdin);
  std::ios_base::sync_with_stdio(false);
  std::cin.tie(NULL);

  fin >> N;
  rep(i, N) { fin >> a[i]; }

  fin >> M;
  int q, x;

  rep(i, M) {
    fin >> q >> x;
    int ans = -INF;
    switch (q) {
      case 0:
        ans = op0(x); break;
      case 1:
        ans = op1(x); break;
      case 2:
        ans = op2(x); break;
    }
    fout << ans << '\n';
  }

  return 0;
}