#P8164. [JOI 2022 Final] 沙堡 2 / Sandcastle 2

[JOI 2022 Final] 沙堡 2 / Sandcastle 2

Problem Description

JOI is playing on the beach. He built a sandcastle. The sandcastle built by JOI is located in a rectangular area on the beach. This rectangular area has HH rows and WW columns. The height of the cell in the ii-th row from top to bottom and the jj-th column from left to right is Ai,jA_{i, j}. Note that all values of Ai,j\boldsymbol{A_{i, j}} are pairwise distinct.

On the sandcastle, JOI performs the following actions.

  1. First, JOI chooses a cell and starts moving from that cell.
  2. Then, from the current cell, he moves to an adjacent cell in one of the four directions: up, down, left, or right. He must move to a cell whose height is lower than the current cell. He may repeat this action zero or more times.

In the end, if we look from above, the cells he has visited will form a rectangle.

Given the height information Ai,jA_{i, j} of each cell, write a program to compute the number of all possible rectangles that can be formed by the cells visited by JOI.

Input Format

The first line contains two positive integers H,WH, W.

The next HH lines follow. The ii-th line contains WW positive integers Ai,1,Ai,2,,Ai,WA_{i, 1}, A_{i, 2}, \ldots, A_{i, W}.

Output Format

Output one line with a single integer, representing the number of all possible rectangles formed by the cells visited by JOI.

1 5
2 4 7 1 5

10

3 2
18 10
19 12
17 13

15

3 5
83 47 36 38 40
13 10 26 68 67
15 19 20 70 90

65

Hint

[Sample Explanation #1]

Since there are 1010 possible rectangles formed by the cells visited by JOI, output 1010.

This sample satisfies the constraints of all subtasks.

[Sample Explanation #2]

Since there are 1515 possible rectangles formed by the cells visited by JOI, output 1515.

This sample satisfies the constraints of subtasks 2,3,4,52, 3, 4, 5.

[Sample Explanation #3]

For example, the following rectangle can be formed by the cells visited by JOI. Since there are 6565 possible rectangles in total, output 6565.

This sample satisfies the constraints of subtasks 2,3,4,52, 3, 4, 5.


[Constraints]

This problem uses bundled testdata.

For 100%100\% of the testdata, 1H,W,HW5×1041 \le H, W, H \cdot W \le 5 \times {10}^4, 1Ai,j1071 \le A_{i, j} \le {10}^7, Ai1,j1Ai2,j2A_{i_1, j_1} \ne A_{i_2, j_2} ((i1,j1)(i2,j2)(i_1, j_1) \ne (i_2, j_2)).

  • Subtask 11 (99 points): H=1H = 1.
  • Subtask 22 (1010 points): HW100H \cdot W \le 100.
  • Subtask 33 (55 points): HW1500H \cdot W \le 1500.
  • Subtask 44 (5656 points): HW7000H \cdot W \le 7000.
  • Subtask 55 (2020 points): no additional constraints.

Translated from JOI 2022 Final T5「砂の城 2 / Sandcastle 2

Translated by ChatGPT 5