Cod sursa(job #1041626)

Utilizator BionicMushroomFMI - Dumitrescu Tiberiu Alexandru BionicMushroom Data 25 noiembrie 2013 22:54:18
Problema Cautare binara Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include<iostream>
#include<fstream>
using namespace std;

ifstream f ("cautbin.in");
ofstream g ("cautbin.out");
int *a, n, m, val;
short code;

int search0 (int val)
{
	int i, step;
	for (step = 1; step < n; step <<= 1);
	for (i = 0; step; step >>= 1)
		if (i + step < n && a[i + step] <= val)
			i += step;
	if (a[i] == val)
		return i;
	else
		return -2;
}

int search1 (int val)
{
	int i, step;
	for (step = 1; step < n; step <<= 1);
	for (i = 0; step; step >>= 1)
		if (i + step < n && a[i + step] <= val)
			i += step;
	return i;
}

int search2 (int val)
{
	int i, step;
	for (step = 1; step < n; step <<= 1);
	for (i = 0; step; step >>= 1)
		if (i + step < n && a[i + step] < val)
			i += step;
	if (i + 1 == n || a[i] == val)
		return i;
	else
		return i + 1;
}

int main ()
{
	f >> n;
	a = new int[n];
	for (int i = 0; i < n; i++)
		f >> a[i];
	f >> m;
	for (int i = 1; i <= m; i++)
	{
		f >> code >> val;
		switch(code)
		{
			case 0:
				g << search0(val) + 1 << '\n';
				break;
			case 1:
				g << search1(val) + 1 << '\n';
				break;
			case 2:
				g << search2(val) + 1 << '\n';
		}
	}
	return 0;
}