Under construction

Still being built. Things may change

New Fountain

Interview

Time limit2sMemory limit1024 MB

Summary
Given an n by m grid of pillar heights, find the maximum total volume of water the grid can hold without draining off the border.
Level

Medium6 of 10

Topics
Heap, BFS, Greedy
Solved
No attempts yet

Statement

Today Lorelin was walking through Alfa when she found a new fountain that will open soon and be filled with water. She wondered how much water the fountain can hold.

The fountain is a set of pillars. Its base is an n×mn \times m rectangular grid divided into nmnm unit squares. Rows are numbered 1 to nn and columns 1 to mm. Each cell holds a pillar of positive integer height, and the pillar in row ii, column jj has height hi,jh_{i,j}.

When the fountain opens, water pours in from above and fills every empty space inside it. Formally, once the fountain opens, each pillar gets a column of water of some non-negative height, possibly zero. Let wi,jw_{i,j} be the water height on the pillar in row ii, column jj. Water does not flow out of the fountain if these conditions hold:

  • If i∈{1,n}i \in \{1, n\} or j∈{1,m}j \in \{1, m\}, then wi,j=0w_{i,j} = 0. In other words, pillars on the border carry no water, and water drains out of the fountain.
  • If ∣i1−i2∣+∣j1−j2∣=1|i_1 - i_2| + |j_1 - j_2| = 1, then either wi1,j1=0w_{i_1,j_1} = 0 or hi1,j1+wi1,j1≤hi2,j2+wi2,j2h_{i_1,j_1} + w_{i_1,j_1} \le h_{i_2,j_2} + w_{i_2,j_2}. In other words, a pillar that holds water has a total height no greater than each of its side neighbors.

The total water volume is the sum of all wi,jw_{i,j}. The fountain fills so that this total is as large as possible.

Lorelin remembers the base size and every pillar height, but she cannot work out the volume. Help her compute it.

Input

The first line contains two integers nn and mm, the number of rows and columns of the base (3≤n,m≤9003 \le n, m \le 900). Each of the next nn lines contains mm integers. Line i+1i + 1 contains hi,1,hi,2,…,hi,mh_{i,1}, h_{i,2}, \dots, h_{i,m}, the heights of the pillars in row ii (1≤hi,j≤1091 \le h_{i,j} \le 10^9).

Output

Print a single number: the maximum total volume of water that can fit in the fountain.

Hint

In the first test, the maximum volume is reached with w2,2=2w_{2,2} = 2, w2,3=1w_{2,3} = 1, and wi,j=0w_{i,j} = 0 for all other pillars. These values clearly satisfy all the conditions, and the total volume is 3.

In the second test, only two pillars can hold water. The maximum volume is reached with w2,2=1w_{2,2} = 1, w2,3=1w_{2,3} = 1, and wi,j=0w_{i,j} = 0 for all other pillars. The total volume is 2.

Examples2

  1. Example 1

    Input
    4 4
    3 4 4 3
    4 1 2 3
    3 4 5 3
    3 1 4 4
    
    Expected output
    3
    
  2. Example 2

    Input
    4 5
    2 2 2 2 2
    2 1 1 2 2
    2 2 2 1 1
    2 2 2 2 2
    
    Expected output
    2