Cod sursa(job #389263)

Utilizator SzabiVajda Szabolcs Szabi Data 1 februarie 2010 13:07:34
Problema Cautare binara Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <stdio.h>
unsigned int n,m;
unsigned int a[100001];

unsigned int ln(unsigned int x){
unsigned int lo=1,hi=n,mid;

while (lo<=hi){
mid=lo+(hi-lo)/2;

if(a[mid]==x){
	if((mid==n)||(a[mid+1]!=a[mid])){return mid;}
	else{lo=mid+1;}
}else{if(x>a[mid]){lo=mid+1;}else{hi=mid-1;}}	


}
return -1;}

unsigned int egyes(unsigned int x){
unsigned int lo=1,hi=n,mid;

while (lo<=hi){
mid=lo+(hi-lo)/2;

if(a[mid]==x){
	if((mid==n)||(a[mid+1]!=a[mid])){return mid;}
	else{lo=mid+1;}
}else{if(x>a[mid]){lo=mid+1;}else{hi=mid-1;}}	


}
return --mid;}



unsigned int kettes(unsigned int x){
unsigned int lo=1,hi=n,mid;

while (lo<=hi){
mid=lo+(hi-lo)/2;

if(a[mid]==x){
	if((mid==1)||(a[mid-1]!=a[mid])){return mid;}
	else{hi=mid-1;}
}else{if(x>a[mid]){lo=mid+1;}else{hi=mid-1;}}	


}
return ++mid;}
int main(){
freopen("cautbin.in","r",stdin);
freopen("cautbin.out","w",stdout);

unsigned int i,temp1,temp2;

scanf("%d",&n);
for (i=1;i<=n;i++){
scanf("%d",&a[i]);

}

scanf("%d",&m);
for (i=1;i<=m;i++){
scanf("%d %d",&temp1,&temp2);

switch(temp1){

case 0:
	printf("%d\n",ln(temp2));
	break;
case 1:
	printf("%d\n",egyes(temp2));
	break;
case 2:
	printf("%d\n",kettes(temp2));
	break;
}

}

return 0;
}