Cod sursa(job #443510)

Utilizator SpiderManSimoiu Robert SpiderMan Data 17 aprilie 2010 10:59:02
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Tema 10D #1 Marime 1.16 kb
#include <fstream>
using namespace std;

int n, m, a,b,v[100005];
ifstream f("cautbin.in");
ofstream g("cautbin.out");

inline int search0(int x)
{
	int st, dr, mij, max = -1;

	for (st = 1, dr = n; st <= dr; )
	{
		mij = st + ((dr-st) >> 1);
		if (x < v[mij]) dr = mij-1;
		else if (v[mij] < x) st = mij+1;
		else max = mij, st = mij+1;
	}
	return max;
}

inline int search1(int x)
{
	int st, dr, mij, max = 0;

	for (st = 1, dr = n; st <= dr; )
	{
		mij = st + ((dr-st) >> 1);
		if (v[mij] <= x) max = mij, st = mij+1;
		else dr = mij-1;
	}
	return max;
}

inline int search2(int x)
{
	int st, dr, mij, min = n+1;

	for (st = 1, dr = n; st <= dr; )
	{
		mij = st + ((dr-st) >> 1);
		if (x <= v[mij]) min = mij, dr = mij-1;
		else st = mij+1;
	}
	return min;
}

void citire()
{
    int i;

    f>>n;
    for (i = 1; i <= n; ++i)
		f>>v[i];
}
void solve()
{
    f>>m;
    for (;m;m--)
    {
        f>>a>>b;
        if (!a) g<<search0(b)<<"\n";
        else if (a==1) g<<search1(b)<<"\n";
        else g<<search2(b)<<"\n";
    }
}
int main()
{
    citire();
    solve();
    f.close();
    g.close();
    return 0;
}