Advanced Eggplant Farm
Time limit3sMemory limit1024 MB
Given a grid of eggplant sizes, assign non-negative integer heights so that each adjacent pair respects the size order, with the minimum total height.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Sorting, Graph, Topological sort
- Solved
- No attempts yet
Problem
Mingu owns an advanced eggplant farm. The farm is a grid of rows and columns, and an eggplant is planted in each of the soil cells. Mingu noticed that eggplants that receive more water grow faster. To even out the sizes, he wants to give more water to the smaller eggplants.
To do this, the height of each soil cell can be changed to any non-negative integer. Water flows from higher ground to lower ground, so more water collects in the lower of two adjacent cells. If two adjacent cells have the same height, the same amount of water collects in each. Two cells are adjacent if they share a side.
To even out the sizes, for every pair of adjacent cells, the soil under the larger eggplant must be higher than the soil under the smaller one. If two adjacent eggplants have the same size, their soil heights must be equal.
Currently, every soil cell has height . Changing the height of one cell to costs units of work, where is a non-negative integer. Find the height arrangement that evens out the sizes and has the minimum total work.
In other words, you are given a matrix of size of positive integers, where is the size of the eggplant in row , column . Find a matrix of size of non-negative integers, where is the height of the soil in row , column , that satisfies the following conditions.
- For all integers with , , and :
- If , then .
- If , then .
- If , then .
- The sum of all elements of is minimal.
Input
The first line contains the number of rows and the number of columns , separated by a space. ()
Each of the next lines contains positive integers separated by spaces, which are the eggplant sizes in that row. The -th number on the -th line is the eggplant size in row , column . ()
Output
Print lines, each containing non-negative integers separated by spaces.
The -th number on the -th line is , the soil height in row , column , in the arrangement with the minimum total work.
The matrix that answers the problem is unique.