UVa 10611 - The Playboy Chimp

Once upon a time, there lived a chimpanzee called Luchu Bandor (aka Playboy Chimp)...

There will be only one set of input for this problem. The first line of input gives you a number N (1 ≤ N ≤ 50000), the number of lady chimps on the line. In the next line you would have N integers (in the range 1 to 2 31 − 1 giving the heights of the N chimps. There would be a single space after every number. You can assume that the chimps are ordered in non-decreasing order of their heights.

In the next line you would have an integer Q (1 ≤ Q ≤ 25000) giving the number of queries. Then in the next line Q queries will follow. Then you would have Q numbers giving the height of Luchu!

For each query height, print two numbers in one line. The first one would be the height of the tallest lady chimp that is shorter than Luchu, and the next number would be the height of the shortest lady chimp that is taller than he. These two numbers are to be separated by a single space. Whenever it is impossible to find any of these two heights, replace that height with an uppercase ‘X’.

Explanation
The problem is handled by a binary search. This requires two searches - a highest value below the target number, and a lowest value above the target number.

Gotchas

 * Any points one can easily overlook?
 * The correct way to understand ambiguous formulations?

Implementations
Notes/Hints on actual implementation here.

Optimizations
Optimizations here.

Input
4 1 4 5 7 4 4 6 8 10

From uDebug, user Morass: 100 2 3 4 6 7 8 8 8 9 11 11 14 18 18 21 23 24 24 24 25 26 30 30 30 30 31 32 32 33 33 35 36 37 40 40 40 40 42 42 43 44 44 44 45 45 45 47 47 49 50 53 53 53 54 55 56 56 56 57 57 58 58 60 62 62 63 63 63 64 66 67 70 71 71 72 73 76 77 80 80 81 82 83 83 84 85 87 90 91 91 91 92 93 94 94 97 98 98 99 99 100 85 78 34 89 85 48 27 5 75 70 75 90 3 65 74 91 82 47 75 27 26 73 88 26 22 37 67 67 20 48 67 4 77 52 93 13 99 71 17 26 92 92 15 95 8 40 37 89 86 63 15 64 35 3 41 56 91 60 23 10 59 41 66 35 93 10 99 91 80 68 16 24 11 82 70 18 21 58 7 59 20 21 22 54 75 14 62 18 73 36 79 31 76 96 17 20 5 16 63 37

Output
1 5 5 7 7 X 7 X