Cod sursa(job #1155178)

Utilizator theodor.moroianuTheodor Moroianu theodor.moroianu Data 26 martie 2014 18:34:17
Problema Cautare binara Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.01 kb
#include <iostream>
#include <fstream>
using namespace std;
void f1(int x);
void f2(int x);
void f3(int x);
int n, m, v[10000], i, b, cit, q;
long long p;
ofstream out("cautbin.out");
int main(){
	ifstream in("cautbin.in");

	in >> n;
	for (i = 0; i < n; i++)
		in >> v[i];
	in >> m;
	for (int k = 1; k <= m; k++){
		in >> q >> cit;
		if (q == 0)
			f1(cit);
		else if (q == 1)
			f2(cit);
		else
			f3(cit);

	}
}
void f1(int x){
	b = 0;
	p = 1 << 10;
	while (p != 0){
		if (b + p<n&&v[b + p] <= x)
			b += p;
		p /= 2;
	}
	if (v[b]<cit)
		out << -1 << "\n";
	else
		out << b + 1 << "\n";
}
void f2(int x){
	b = 0;
	p = 1 << 10;
	while (p != 0){
		if (b + p<n&&v[b + p] <= x)
			b += p;
		p /= 2;
	}
	out << b + 1 << "\n";
}
void f3(int x){
	if (v[0] >= x){
		out << 1 << "\n";
		return;
	}
	b = p = 1 << 10;
	while (p != 0){
		if (b - p>0 && v[b - p] >= x || b - p>n)
			b -= p;
		p /= 2;
	}
	if (b + 1>n){
		out << n << "\n";
		return;
	}
	out << b + 1 << "\n";
}