Cod sursa(job #2429532)

Utilizator pickleVictor Andrei pickle Data 9 iunie 2019 23:18:53
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <stdio.h>
#include <bits/stdc++.h>

#define rep(i, n) for(int i = 0; i < n; i++)
#define repa(i, l, r) for (int i = l; i < r; i++)
#define repd(i, r, l) for (int i = r; i > l; i--)

using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
ifstream fin ("cautbin.in");
ofstream fout ("cautbin.out");
const int Nmax = 100555;
int N, M;
int a[Nmax];

int op_01(int x) {
  // cea mai mare pozitie cu un element <= x.
  int step = 1, i;
  while(step < N) step *= 2;
  for(i = 0; step; step /= 2)
    if (i+step < N && a[i+step] <= x)
      i += step;
  return i;
}
int op_2(int x) {
  // cea mai mica pozitie cu un element >= x.
  int step = 1, i;
  while(step < N) step *= 2;
  for(i = N-1; step; step /= 2)
    if (i-step >= 0 && a[i-step] >= x)
      i -= step;
  return i;
}

int main(void) {
  fin >> N;
  rep(i, N)
    fin >> a[i];

  fin >> M;
  int q,x;

  rep(i,M) {
    fin >> q >> x;
    if (q==0) {
      // cea mai mare pozitie cu un element = x (or -1).
      int res = op_01(x);
      fout << (a[res] == x ? res+1 : -1) << '\n';
    } else if (q == 1) {
      // cea mai mare pozitie cu un element <= x.
      fout << op_01(x)+1 << '\n';
    } else {
      // cea mai mica pozitie cu un element >= x.
      fout << op_2(x)+1 << '\n';
    }
  }

  return 0;
}