The Intervals


Time Limit: 1 Second      Memory Limit: 32768 KB


Cantor, the famous mathematician, was working on a problem about intervals.

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?

ZOJ 2029 The Intervals_arrays

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

 


Author: SHI, Xiaohan
Source: ZOJ Monthly, November 2003

解题:

       问题是求b数组里面的每个数在a数组里的区间,适合用二分法查找,但要先排序。注意可能a数组里面有相同数字,我的处理是不读入。自己用的STL+二分法。不够简洁~~~

#include <iostream> #include <algorithm> #include <vector> using namespace std; int BinSearch(vector<int> intVector,int n,int k) { n=intVector.size(); int low=0,high=n-1,mid; if (k<intVector.at(0) || k>=intVector.at(n-1)) { return -1; } while (low<=high) { mid=(low+high)/2; if (intVector.at(mid)==k) { return mid; } else if (intVector.at(mid)>k) { high=mid-1; } else { low=mid+1; } } return low-1; } int main() { int n,m,i,flag,k; vector<int> intVector; vector<int>::iterator iter; vector<int> intVector2; while (cin>>n>>m) { for (i=0;i<n;i++) { cin>>k;flag=0; for (iter=intVector.begin();iter!=intVector.end();iter++) { if (*iter==k) { flag=1; break; } } if (flag==0) { intVector.push_back(k); } } for (i=0;i<m;i++) { cin>>k; intVector2.push_back(k); } sort(intVector.begin(),intVector.end()); for (iter=intVector2.begin();iter!=intVector2.end();iter++) { k=BinSearch(intVector,n,*iter); if (k!=-1) { cout<<"["<<intVector.at(k)<<","<<intVector.at(k+1)<<")"<<endl; } else { cout<<"no such interval"<<endl; } } puts(""); intVector.clear(); intVector2.clear(); } return 0; }