Cod sursa(job #702760)

Utilizator romircea2010FMI Trifan Mircea Mihai romircea2010 Data 2 martie 2012 09:07:24
Problema Cautare binara Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include <fstream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <iostream>

using namespace std;

int n, k, a[100005];

int cautare(int x)
{
	int m, st, dr, poz;
	poz = -1;
	st = 0;
	dr = n-1;
	while (poz == -1 && st<=dr)
	{
		m = (st + dr)/2;
		if (a[m] == x)
			poz = m;
		if (a[m] < x)
			st = m+1;
		else
			dr = m-1;			
	}
	return poz;
}

int main()
{
	ifstream f("cautbin.in");
	f>>n;
	int i;
	for (i=0; i<n; i++)
		f>>a[i];
	f>>k;
	int x, y, *p, j, poz;
	ofstream g("cautbin.out");
	for (j=0; j<k; j++)
	{
		f>>x>>y;
		if (x == 0)
		{
			poz = cautare(y);
			if (poz == -1)
				g<<poz<<"\n";
			else
			{
				while (a[poz] == y)
					poz++;
				poz--;
				g<<poz+1<<"\n";
			}
			continue;
		}
		if (x == 1)
		{
			p = upper_bound(a, a+n, y);
			poz = p - a;
			if (a[poz] == y)
				g<<poz+1<<"\n";
			else
			{
				while(a[poz]>y)
					poz--;
				g<<poz+1<<"\n";
			}
			continue;
		}
		if (x == 2)
		{
			p = lower_bound(a, a+n, y);
			poz = p - a;
			while (a[poz]<y)
				poz++;
			g<<poz+1<<"\n";
		}
	}
	f.close();
	g.close();
	return 0;
}