Cod sursa(job #2667358)

Utilizator alexandrubunea03Bunea Alexandru alexandrubunea03 Data 3 noiembrie 2020 13:05:10
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.72 kb
#include <bits/stdc++.h>
using namespace std;
#define debug_var(x) cout << #x << '=' << x << endl;
#define debug_stl(x) for(auto k : x) cout << k << ' '; cout << endl;
#define debug_map(x) for(auto k : x) cout << k.first << ':' << k.second << endl;
#define read_vector(x, s, k) for(auto i = s; i <= k; ++i) cin >> x[i];
#define read_2dvector(x, s, l1, l2) for(auto i = s; i <= l1; ++i) for(auto j = s; j <= l2; ++j) cin >> x[i][j];
#define vec vector
#define ull unsigned long long int
#define ll long long int
#define str string
#define umap unordered_map
#define uset unordered_set
#define mset multiset
#define umset unordered_multiset
#define NMax 100000

int v[NMax], n, m;

int bin_search_one(int x) {
  int i, step;
  for(step = 1; step < n; step <<= 1);
  for(i = 0; step; step >>= 1) {
    if(i + step < n && v[i + step] == x) {
      i += step;
    }
  }
  if(v[i] == x) return i;
  return -1;
}
int bin_search_two(int x) {
  int i, step;
  for(step = 1; step < n; step <<= 1);
  for(i = 0; step; step >>= 1) {
    if(i + step < n && v[i + step] <= x) {
      i += step;
    }
  }
  return i;
}
int bin_search_three(int x) {
  int i, step;
  for(step = 1; step < n; step <<= 1);
  for(i = n - 1; step; step >>= 1) {
    if(i - step > 0 && v[i - step] >= x) {
      i -= step;
    }
  }
  return i;
}

int main() {
  freopen("cautbin.in", "r", stdin);
  freopen("cautbin.out", "w", stdout);
  ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
  cin >> n;
  read_vector(v, 0, n - 1);
  cin >> m;
  for(int i = 0; i < m; ++i) {
    int type, x;
    cin >> type >> x;
    if(!type) cout << bin_search_one(x) + 1 << '\n';
    if(type == 1) cout << bin_search_two(x) + 1 << '\n';
    if(type == 2) cout << bin_search_three(x) + 1 << '\n';
  }
  return 0;
}