Cod sursa(job #608428)

Utilizator selea_teodoraSelea Teodora selea_teodora Data 16 august 2011 17:29:07
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include<fstream>
using namespace std;
int n,m, v[100005],val;
int cautare_bin1(int st,int dr,int x)
{
	int mij;
	while(st<=dr)
		{
			mij=st+(dr-st)/2;
			if(v[mij]<=x)
				st=mij+1;
			else
				dr=mij-1;
	}
	mij=st+(dr-st)/2;
	if(v[mij]>x)
		mij--;
	if(v[mij]==x)
		return mij;
	return -1;
}
int cautare_bin2(int st,int dr,int x)
{
	int mij;
	while(st<=dr)
	{
		mij=st+(dr-st)/2;
		if(v[mij]<=x)
			st=mij+1;
		else
			dr=mij-1;
	}
	mij=st+(dr-st)/2;
	if(v[mij]>x)
		mij--;
	//if(v[mij]<=x)
		return mij;
}
int cautare_bin3(int st,int dr,int x)
{
	int mij;
	if(st<=dr)
	{
		mij=st+(dr-st)/2;
		if(v[mij]<x)
			st=mij+1;
		else
			dr=mij-1;
	}
	mij=st+(dr-st)/2;
	if(v[mij]<x)
		mij++;
	//if(v[mij]>=x)
		return mij;
}
int main()
{
	ifstream fin("cautbin.in");
	ofstream fout("cautbin.out");
	fin>>n;
	int i;
	for(i=1;i<=n;i++)
		fin>>v[i];
	fin>>m;
	int x;
	for(i=1;i<=m;i++)
	{
		fin>>val>>x;
		if(val==0)
		{
			//fin>>x;
			//int poz=0;
			fout<<cautare_bin1(1,n,x)<<endl;
			//fout<<poz<<endl;
		}
		else
			if(val==1)
			{
				//fin>>x;
				//int poz=0;
				fout<<cautare_bin2(1,n,x)<<endl;
				//fout<<poz<<endl;
			}
		else
			if(val==2)
		{
			//fin>>x;
			int poz=0;
			fout<<cautare_bin3(1,n,x)<<endl;
			//fout<<poz<<endl;
		}
	}
	fin.close();
	fout.close();
	return 0;
}