Quality of Living
InterviewTime limit5sMemory limit256 MB
Find the smallest median among all H by W subrectangles of a grid holding the numbers 1 to R times C.
- Level
Medium6 of 10
- Topics
- Binary search, Prefix sum, Matrix
- Solved
- No attempts yet
Problem
The city of Alberta is laid out as a rectangular grid of blocks. Rows are numbered from in the north to in the south, and columns from in the west to in the east.
The quality of living of each block is written as one distinct integer between and , called its quality rank. The block with quality rank has the best quality of living, and the block with quality rank has the worst.
Hongjun looks only at regions that fit entirely inside the grid. and are odd, and , . For an odd number of quality ranks, the median is the value that has as many better ranks as worse ranks.
Every region has one median quality rank. Write a program that finds the best of those medians, that is, the smallest one.
Input
The first line contains the integers , , , , separated by spaces. and are the number of rows and columns of the city, and and are the number of rows and columns of the region Hongjun picked. and are odd, with and .
Each of the next lines contains integers. The -th number on the -th line is the quality rank of the block in row and column . The numbers on the grid are the integers from to , each appearing exactly once.
Output
Print the smallest median over all regions on the first line.