Cod sursa(job #3152228)

Utilizator sorinturdaSorin Turda sorinturda Data 24 septembrie 2023 13:43:26
Problema Cautare binara Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
//https://www.infoarena.ro/problema/cautbin
#include <bits/stdc++.h>

using namespace std;

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


void b1(int *a, int n, int x){
	int st=0,dr=n-1,mid;
	while(st <= dr){
		mid = st + (dr-st)/2;
		if(a[mid] <= x)
			st = mid + 1;
		else
			dr = mid - 1;
	}
	if(a[dr]==x)
		cout<<dr+1;
	else
		cout<<-1;
}

void b2(int *a, int n, int x){
	int st=0,dr=n-1,mid;
	while(st <= dr){
		mid = st + (dr-st)/2;
		if(a[mid] <= x)
			st = mid + 1;
		else
			dr = mid - 1;
	}
	if(a[dr]==x)
		cout<<dr+1;
	else
		cout<<-1;
}
void b3(int *a, int n, int x){
	int st=0,dr=n-1,mid;
	while(st <= dr){
		mid = st + (dr-st)/2;
		if(a[mid] < x)
			st = mid + 1;
		else
			dr = mid - 1;
	}
	if(a[st]==x)
		cout<<st+1;
	else
		cout<<-1;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int n;
    in>>n;
    int a[100000];
    for(int i=0;i<n;i++)
    	in>>a[i];
   	int m;
   	in>>m;

   	for(int i=0;i<m;i++){
   		int x, y;
   		in>>y>>x;
   		if(y==0)
   			b1(a, n,x);
   		if(y==1)
   			b2(a, n,x);
   		if(y==2)
   			b3(a, n,x);
   		cout<<'\n';
   	}
    return 0;
}