Cod sursa(job #633700)

Utilizator johnny2008Diaconu Ion johnny2008 Data 14 noiembrie 2011 16:18:29
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.04 kb
#include<fstream>
#include<iostream>
using namespace std;
int a[100001],n,m;
int cauta1(int lol,int f,int l){
	int me=(f+l)/2;
	if(f==l && a[me]!=lol)
		return -1;
	
	if(a[me]==lol)
		return me;
	else
		if(lol>a[me])
			return cauta1(lol,me,l);
		else
			return cauta1(lol,f,me);
}
int cauta2(int lol,int f,int l){
	int me=(f+l)/2;
	if(f==l && a[me]!=lol)
		return me;
	
	if(a[me]==lol)
		return me;
	else
		if(lol>a[me])
			return cauta1(lol,me,l);
		else
			return cauta1(lol,f,me);
}

int main(){
	ifstream f("cautbin.in");
	ofstream g("cautbin.out");
	f>>n;
	int i;
	for(i=1;i<=n;i++){
		f>>a[i];
	}
	f>>m;
	int x,y;
	for(i=1;i<=m;i++){
		f>>x>>y;
		if(x==0){
			x=cauta1(y,1,n);
			while(a[x]==y){
				x++;
			}
			g<<x-1<<'\n';
		}
		else
			if(x==1){
				x=cauta2(y,1,n);
				while(a[x]>y){
					x--;
				}
				while(a[x]==a[x+1]){
					x++;
				}				
				g<<x<<'\n';
			}
			else{
				x=cauta2(y,1,n);
				while(a[x]<y){
					x++;
				}
				g<<x-1<<'\n';
			}
				
	}
	return 0;
}