Tractor
Time limit1sMemory limit128 MB
Find the smallest cost c so that a connected region of at least half the N x N grid is reachable using only steps whose elevation difference is at most c.
- Level
Medium6 of 10
- Topics
- Binary search, Union-find, Graph, Sorting
- Solved
- No attempts yet
Problem
One of Farmer John's fields is especially hilly, and he wants to buy a new tractor to drive around on it. The field is given as an grid of non-negative integer elevations (); the value in each cell is that cell's elevation.
A tractor may move only one step at a time, to a cell adjacent to the north, east, south, or west. If you buy a tractor of cost , it can move freely between any two adjacent cells whose elevation difference is at most (a step across an elevation difference greater than is impossible).
Farmer John wants to be able to start from some cell and visit at least half of all the cells in the field (rounded up if the number of cells is odd). Compute the minimum cost of a tractor that makes this possible.
Input
- Line 1: the integer .
- Lines 2 to : each line contains space-separated non-negative integers describing one row of the field. Each elevation is at most 1,000,000.
Output
- Print a single line with the minimum cost of a tractor able to drive around at least half of the field.
Hint
In the example input the field is a grid, so the tractor must visit at least 13 of the 25 cells. A tractor of cost 3 can move between elevation 0 and elevation 3, so it can reach the region of cells at elevation 0 together with the region of cells at elevation 3. Together these make up at least half of the field, so the answer is 3.