← Home
write a go solution for Description:
One fine day Sasha went to the park for a walk. In the park, he saw that his favorite bench is occupied, and he had to sit down on the neighboring one. He sat down and began to listen to the silence. Suddenly, he got a question: what if in different parts of the park, the silence sounds in different ways? So it was. Let's divide the park into 1x1 meter squares and call them cells, and numerate rows from 1 to n from up to down, and columns from 1 to m from left to right. And now, every cell can be described with a pair of two integers (x,y), where x — the number of the row, and y — the number of the column. Sasha knows that the level of silence in the cell (i,j) equals to f_i,j, and all f_i,j form a permutation of numbers from 1 to n*m. Sasha decided to count, how many are there pleasant segments of silence?

Let's take some segment [lldotsr]. Denote S as the set of cells (i,j) that l<=f_i,j<=r. Then, the segment of silence [lldotsr] is pleasant if there is only one simple path between every pair of cells from S (path can't contain cells, which are not in S). In other words, set S should look like a tree on a plain. Sasha has done this task pretty quickly, and called the algorithm — "algorithm of silence's sounds".

Time passed, and the only thing left from the algorithm is a legend. To prove the truthfulness of this story, you have to help Sasha and to find the number of different pleasant segments of silence. Two segments [l_1ldotsr_1], [l_2ldotsr_2] are different, if l_1neql_2 or r_1neqr_2 or both at the same time.

Input Format:
The first line contains two integers n and m (1<=n,m<=1000, 1<=n*m<=2*10^5) — the size of the park.

Each from next n lines contains m integers f_i,j (1<=f_i,j<=n*m) — the level of silence in the cell with number (i,j).

It is guaranteed, that all f_i,j are different.

Output Format:
Print one integer — the number of pleasant segments of silence.

Note:
In the first example, all segments of silence are pleasant.

In the second example, pleasant segments of silence are the following:. Output only the code with no comments, explanation, or additional text.