Time Limit: 1 Second Memory Limit: 32768 KB
Given two arrays of numbers {A(n)} and {B(m)}. For each B(i) in {B(m)}, find 2 numbers a and b from {A(n)}, such that B(i) is in [a,b) and b-a<=|b'-a'| for all a' and b' from {A(n)} such that [a',b') contains B(i).
Input
There are several test cases.
In each test case, the first line gives n and m.
The second line contains n numbers, which are the elements of {A(n)}.
The third line contains m nubmers, which are the elements of {B(m)}.
Output
For each B(i) in {B(m)}, output a line containing the interval [a,b).
If there is no such interval, output "no such interval" instead.
Print a blank line after each test case.
Sample Input
3 3
10 20 30
15 25 35
Sample Output
[10,20)
[20,30)
no such interval
/*题目要求找中间值,所以先排序比较好解,二分查找比顺序查找快,要灵活运用还要有创造力,把二分查找返回条件改写一下就能完成这道题了,若值不在最大或最小范围内则输出nosuch intervals,注意条件每个案例后面输出一个空行*/
#include<stdio.h>
#include<stdlib.h>
int a[1000],mid,low,high;
int comp(const void *a,const void *b)
{
return *(int *)a-*(int *)b;
}
int search(int n,int k)
{
low=0,high=n-1,mid;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]<=k&&a[mid+1]>k) return(mid);
if(a[mid]>k)
high=mid-1;
else low=mid+1;
}
return -1;
}
int main()
{ int b;
register int i;
int m,n;
while(scanf("%d%d%*c",&m,&n)!=EOF)
{
for(i=0;i<m;i++)
scanf("%d",&a[i]);
qsort(a,m,sizeof(int),comp);
for(i=0;i<n;i++)
{
scanf("%d",&b);
if(b<a[0]||b>=a[m-1]||search(m,b)==-1) {printf("no such interval/n");continue;}
printf("[%d,%d)/n",a[mid],a[mid+1]);
}
printf("/n");
}
return 0;
}