Cod sursa(job #608418)

Utilizator selea_teodoraSelea Teodora selea_teodora Data 16 august 2011 16:42:37
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include<fstream>
using namespace std;
int n,m, v[100005],val,x;
void cautare_bin1(int st,int dr,int&poz)
{
	int mij;
	if(dr>st)
	{
		mij=st+(dr-st)/2;
		if(v[mij]==x)
			{
				poz=mij;
				cautare_bin1(st+1,dr,poz);
		}
		else
			if(v[mij]<x)
				cautare_bin1(st,mij,poz);
			else
				cautare_bin1(st+1,dr,poz);
	}
}
void cautare_bin2(int st,int dr,int&poz)
{
	int mij;
	if(st<dr)
	{
		mij=st+(dr-st)/2;
		if(v[mij]==x)
		{
			poz=mij;
			cautare_bin2(st+1,dr,poz);
		}
		else
			if(v[mij]<x)
				poz=mij;
	}
}
void cautare_bin3(int st,int dr,int&poz)
{
	int mij;
	if(st<dr)
	{
		mij=st+(dr-st)/2;
		if(v[mij]==x)
		{
			poz=mij;
			cautare_bin3(st,mij,poz);
		}
		else
			if(v[mij]>x)
				poz=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;
	for(i=1;i<=m;i++)
	{
		fin>>val>>x;
		if(val==0)
		{
			//fin>>x;
			int poz=0;
			cautare_bin1(1,n,poz);
			if(poz==0)
				fout<<-1<<endl;
			else
				fout<<poz<<endl;
		}
		else
			if(val==1)
			{
				//fin>>x;
				int poz=0;
				cautare_bin2(1,n,poz);
				fout<<poz<<endl;
			}
		else
			if(val==2)
		{
			//fin>>x;
			int poz=0;
			cautare_bin3(1,n,poz);
			fout<<poz<<endl;
		}
	}
	fin.close();
	fout.close();
	return 0;
}