by 23423LA » Wed Sep 20, 2006 12:24 pm
Is the description is not strong enough?
Here's my code. I havent inserted the duplicate inputs.
// The PlayBoy Chimp (10611)
// 20.09.06
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
long arr[50009];
int comp(const void *a,const void *b);
void main()
{
long key,index,i,data,n1;
long *p;
long n,height,node_no;
bool flag;
scanf("%ld",&n);
n1=n;
node_no=0;
while(n--)
{
scanf("%ld",&data);
flag=false;
if(node_no==0) //no duplicate will be in stored array
{
arr[node_no]=data;
node_no++;
flag=true;
}
else
{
if(arr[node_no-1]==data)
flag=true;
}
if(flag==false)
{
arr[node_no]=data;
node_no++;
}
}
n=n1;
scanf("%ld",&height);
i=0; // searching starts
while(height)
{
height--;
scanf("%ld",&key);
p=(long *)bsearch(&key,arr,n,sizeof(long),comp);
if(p)
index=p-arr;
else
index=-1;
if(arr[index]==key) //if height_i found
{
if((index-1)<0)
printf("%c ",'X');
else
{
printf("%ld ",arr[index-1]);
}
}
else if(index==-1) //not found in max index
printf("%ld ",arr[node_no-1]);
else if(arr[index]>key && index>0)
printf("%ld ",arr[index-1]);
else if(arr[index]>key && index==0) //if less than 1st element
printf("X ");
if(arr[index]==key)
{
if(index+1<node_no)
printf("%ld\n",arr[index+1]);
else
printf("X\n");
}
else if(index==-1)
printf("X\n");
else if(arr[index]>key)
printf("%ld\n",arr[index]);
i++;
}
}
int comp(const void *a,const void *b)
{
long *A=(long *)a; //key
long *B=(long *)b; //current
if(*A<*B && (B-arr==0 || *A>*(B-1)))
return 0;
return *A-*B;
}