Description
Let's start from a line segment of unit length. Remove its middle 1/3.
Now remove the middle 1/3's from the remaining two segments.
Now remove the middle 1/3's from the remaining four segments.
Now remove the middle 1/3's from the remaining eight segments.
Now remove ... well, you get the idea.
If you could continue this procedure through infinitely many steps, what would you have left?
Now he assigns the following task to you. (He asked me to pass his assignment to you last night.)
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
这道题就是在A数组中任意找一个区间[a,b),使得B[i]属于此区间,并且此区间长度最小。
其实就是一个排序就可以了,找恰好的那个区间。
#include <stdio.h>
#include <algorithm>
const int maxn = 10005;
int a[maxn], b[maxn];
void read ( int a[], int n )
{
for ( int i = 0; i < n; i ++ )
scanf ( "%d", &a[i] );
}
int main ( )
{
int n, m, left;
while ( ~ scanf ( "%d%d", &n, &m ) )
{
read ( a, n );
read ( b, m );
std :: sort ( a, a+n ); //只需要排一次序就行了
for ( int i = 0; i < m; i ++ )
{
left = -1;
int j = 0;
while ( j < n && a[j] <= b[i] )
{
left = a[j]; //找到恰好比b[i]大的数
j ++;
}
if ( j >= n || left == -1 ) //注意需要考虑left=-1证明左边没有
printf ( "no such interval\n" );
else //否则就是输出相邻两个
printf ( "[%d,%d)\n", left, a[j] );
}
printf ( "\n" );
}
return 0;
}