WATER - Water among Cubes

On a rectangular mesh comprising n*m fields, n*m cuboids were put, one cuboid on each field. A base of each cuboid covers one field and its surface equals to one square inch. Cuboids on adjacent fields adhere one to another so close that there are no gaps between them. A heavy rain pelted on a construction so that in some areas puddles of water appeared. 


Write a program which: 

  • reads from the standard input a size of the chessboard and heights of cuboids put on the fields,
  • computes maximal water volume, which may gather in puddles after the rain,
  • writes results in the standard output.


The number of test cases t is in the first line of input, then t test cases follow separated by an empty line. In the first line of each test case two positive integers 1 <= n <= 100, 1 <= m <= 100 are written. They are the size of the mesh. In each of the following n lines there are m integers from the interval [1..10000]; i-th number in j-th line denotes a height of a cuboid given in inches put on the field in the i-th column and j-th raw of the chessboard.


Your program should write for each tes case one integer equal to the maximal volume of water (given in cubic inches), which may gather in puddles on the construction. 


Sample input:
3 6
3 3 4 4 4 2
3 1 3 2 1 4
7 3 1 6 4 1

Sample output:

The picture below shows the mesh after the rain (seen from above). Puddles are drawn in gray.

hide comments
deadbrain: 2017-03-30 08:59:52

well this is one of those problems which require basic knowledge with awesome logics... thanks for the problem.

tni_mdixit: 2017-02-26 23:18:02

a better explanation would be to seek the possible opening from where the water may leak... i. e. the least high column on the boundary!
if we start from that itself, we can fill the water in the columns approachable from that column and it will not leak! :D

ayush5148: 2017-01-02 22:40:08

Finally AC after 7 days............start from the minimum height and then to the maximum height......

suraj_: 2016-10-21 20:57:58

Finally AC !!!!!!! my 46th. @crypt is right
HINT--start from the minimum height and gradually fill the water

Last edit: 2016-10-21 21:03:30
Aayush Sharda: 2016-09-12 12:12:34

@crypt shouldn't the answer for your mentioned test case be 76.

Sarthak Munshi: 2016-08-15 13:27:00

This problem requires a very advance thought process . :p AC after 3 days .

misawa: 2016-07-30 09:54:32

great problem :)

buttman: 2016-05-13 20:56:35

bfs/dfs doesn't get any better than this :)

|RAMSDEN|: 2016-04-02 19:41:56

n^2 log(n) dijkshtra :)

minhthai: 2016-04-02 09:29:21

very nice logic, thanks :)

Added by:Piotr Łowiec
Time limit:7s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: NODEJS PERL6 VB.NET
Resource:6th Polish Olympiad in Informatics, stage 3