Problem 709
Row with Maximum 1s
Easy · 10 pts · Matrix, Binary Search
Problem
Every row of a binary matrix is sorted: all its 0s come before all its 1s. Find the row that contains the most 1s and print its index (counting from 0). If several rows tie, print the smallest index; if the matrix has no 1 at all, print -1. In each row, a binary search for the first 1 gives the count of 1s as C minus that position, for O(R log C) in total.
Input
The first line contains R and C. Each of the next R lines contains C values, each 0 or 1, sorted in non-decreasing order.
Output
Print the index of the row with the most 1s, or -1.
Constraints
1 <= R, C <= 1000; every row is sorted
Example input
3 4 0 0 1 1 0 1 1 1 0 0 1 1
Example output
1
Explanation
In the matrix 0 0 1 1 / 0 1 1 1 / 0 0 1 1, the rows have 2, 3 and 2 ones. Row 1 has the most, so the answer is 1.