Land Purchase
InterviewTime limit2sMemory limit512 MB
Given an r by s grid of cell prices and two numbers a and b, find the nonempty rectangle whose total price minimizes |x-a| + |x-b|.
- Level
Medium6 of 10
- Topics
- Prefix sum, Two pointers, Matrix
- Solved
- No attempts yet
Problem
Matej is the biggest innovator and businessman in Croatia. His company is expanding, so he wants to buy a plot of land near Velika Gorica. The land is a rectangle of unit cells. Each cell has its own price, and a cell cannot be bought in part. Matej wants the price of his plot to be as close as possible to two magic numbers and given by Milan the psychic. The distance between a price and one magic number is the absolute value of their difference. The distance between a price and both magic numbers is the sum of these two absolute differences. Find the minimum possible distance for a nonempty rectangular plot.
Input
The first line contains positive integers , , and (, ).
The -th of the following lines contains positive integers (), the prices of the cells in that row, in order.
Output
Print the minimum possible distance between the price of the plot and the two magic numbers.
Hint
In the second sample, Matej can buy a plot of two adjacent cells, each costing . The total price is , and its distance to the magic numbers is .