Problem 378
Median of a Row-Sorted Matrix
Hard · 30 pts · Matrix, Binary Search
Problem
An R x C matrix has every row sorted in non-decreasing order, and R · C is odd. Find the median of all its elements, that is, the middle value if all R · C elements were put into one sorted list. Instead of merging everything, binary search on the value: for a candidate value V, count how many elements are at most V using a binary search in each row. The median is the smallest V for which more than half of the elements are at most V.
Input
First line: R and C (R · C is odd). Next R lines: C integers each, every row sorted.
Output
Print the median.
Constraints
1 <= R, C <= 500; R · C is odd; 1 <= value <= 1000000000
Example input
3 3 1 3 5 2 6 9 3 6 9
Example output
5
Explanation
The rows 1 3 5, 2 6 9 and 3 6 9 hold 1 2 3 3 5 6 6 9 9 when merged. The middle (5th) of these nine values is 5.