Cod sursa(job #2667377)

Utilizator alexandrubunea03Bunea Alexandru alexandrubunea03 Data 3 noiembrie 2020 13:17:36
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 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 + 1], n, m;

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, 1, n);
  cin >> m;
  int logN;
  for(logN = 1; logN <= n; logN <<= 1);
  for(int i = 0; i < m; ++i) {
    int type, x, j, lg;
    cin >> type >> x;
    if(type < 2) {
      for(j = 1, lg = logN; lg; lg >>= 1) {
        if(j + lg <= n && v[j + lg] <= x) j += lg;
      }
      if(!type && v[j] != x) cout << -1 << '\n';
      else cout <<j<< '\n';
    } else {
      for(j = n, lg = logN; lg; lg >>= 1) {
        if(j - lg > 0 && v[j - lg] >= x) {
          j -= lg;
        }
      }
      cout <<j<< '\n';
    }
  }
  return 0;
}