Cod sursa(job #349729)

Utilizator AstronothingIulia Comsa Astronothing Data 21 septembrie 2009 13:42:08
Problema Cautare binara Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 kb
#include <fstream>
#include <iostream>

using namespace std;

int n,v[100002];

int bspos(int x)
{
    int li = 1, lf = n;
    while(li<=lf)
    {
        int mid = li+(lf-li)/2;
        if(v[mid]==x) return mid;
        if(v[mid]>x) lf = mid-1;
        else li = mid+1;
    }
    return li;
}

int main()
{
	ifstream f("cautbin.in");
	ofstream f2("cautbin.out");

	f>>n;
	for(int i=1; i<=n; ++i) f>>v[i];
	int m;
	f>>m;
	int x,y;
	while(f>>y>>x)
	{
	    int pos = bspos(x);
	    switch(y)
	    {
	        case 0:
	        {
	            if(v[pos]!=x) f2<<"-1\n";
	            else
	            {
	                while(pos<=n && v[pos]==x) ++pos;
	                f2<<pos-1<<"\n";
	            }
	            break;
	        }
	        case 1:
	        {
	            if(v[pos]>x) f2<<pos-1<<"\n";
	            else
	            {
	                while(pos<=n && v[pos]==x) ++pos;
	                f2<<pos-1<<"\n";
	            }
	            break;
	        }
	        case 2:
	        {
	            if(v[pos]!=x) f2<<pos<<"\n";
	            else
	            {
	                while(pos>=1 && v[pos]==x) --pos;
	                f2<<pos+1<<"\n";
	            }
	            break;
	        }
	    }
	}
	return 0;
}