Cod sursa(job #704450)

Utilizator t.valentinoRemus Tumac t.valentino Data 2 martie 2012 18:05:31
Problema Cautare binara Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include<cstdio>
using namespace std;

int n,m,v[100010],i,tip,x;
int rez0,rez1,rez2;

int cautbine0 (int a)
{
	int mij=1,st=1,dr=n;
	rez0=-1;
	while (st<=dr){
		mij=st+(dr-st)/2;
		if (v[mij]==a){
			while (v[mij]==a){
				rez0=mij;
				mij++;
			}
			return rez0;
		}
		else{
			if (v[mij]>a)
				dr=mij-1;
			else
				st=mij+1;
		}
	}
	return -1;
}

int cautbine1(int a)
{
	int st=1,dr=n,mij=1;
	while (st<=dr&&mij<n){
		mij=st+(dr-st)/2;
		if (v[mij]>a)
			dr=mij-1;
		else
			st=mij+1;
	}
	mij=(st+dr)/2;
	if (v[mij]>a)
		mij--;
	return mij;
	
}	

int cautbine2(int a)
{
	int st=1,dr=n,mij=1;
	while (st<=dr){
		mij=st+(dr-st)/2;
		if (v[mij]>a)
			dr=mij-1;
		else
			st=mij+1;
	}
	mij=(st+dr)/2;
	if (v[mij]<a)
		mij++;
	return mij;
	
}

int main()
{
	freopen("cautbin.in","r",stdin);
	freopen("cautbin.out","w",stdout);
	
	scanf("%d",&n);
	for (i=1;i<=n;i++)
		scanf("%d",&v[i]);
	scanf("%d",&m);
	cautbine1(25);
	for (i=1;i<=m;i++){
		scanf ("%d %d",&tip,&x);
		if (tip==0){
			rez0=cautbine0(x);
			printf("%d\n",rez0);
		}
		if (tip==1){
			rez1=cautbine1(x);
			printf("%d\n",rez1);
		}
		if (tip==2){
			rez2=cautbine2(x);
			printf("%d\n",rez2);
		}
	}
	
	return 0;

}