Cod sursa(job #2642850)

Utilizator am_I_reallymeMircea Filat am_I_reallyme Data 17 august 2020 13:38:14
Problema Cautare binara Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
struct my_timer{
	chrono::time_point<chrono::high_resolution_clock> start;
	my_timer():
	start(chrono::high_resolution_clock::now()){}
	~my_timer(){
		std::chrono::duration<double> diff = chrono::high_resolution_clock::now() - start;
		clog<<diff.count()<<"s\n";
	}
};

int vec[100000];
int n;
int under_upper(int val){
	int ret = 0;
	for(int i = 17; i;)
		-- i, ret |= ((ret | (1 << i)) < n && vec[ret | (1 << i)] <= val) << i;
	return ret;
}
int lower_bound(int val){
	int ret = 0;
	for(int i = 17; i;)
		-- i, ret |= ((ret | (1 << i)) < n && vec[ret | (1 << i)] < val) << i;
	return ret + (vec[ret] < val);
}
int main()
{
	freopen("cautbin.in", "r", stdin);
	freopen("cautbin.out", "w", stdout);
	scanf("%d", &n);
	for(int i = 0; i != n; ++ i)
		scanf("%d", &vec[i]);
	int m;
	scanf("%d", &m);
	for(int i = 0; i != m; ++ i){
		int c, val;
		scanf("%d%d", &c, &val);
		if(c == 2)
			printf("%d\n", lower_bound(val) + 1);
		else{
			int pos = under_upper(val);
			if(vec[pos] == val || c == 1)
				printf("%d\n", pos + 1);
			else
				printf("-1\n");
		}
	}
}