Pizza Boxes

Given a grid of distinct pile heights, find how many boxes can be removed while keeping the per-row and per-column maxima unchanged.

Medium4ArrayGreedyImplementationMathInterviewNo attempts yetTime limit1sMemory limit512 MB

Problem

All pizza boxes have the same size. The boxes are stacked into one pile per cell of an nn by mm grid, and every pile has a different height. Seen from the front, the grid shows the height of the tallest pile in each column. Seen from the side, it shows the height of the tallest pile in each row.

Find the largest number of boxes you can remove while both views stay the same. Figure I.1(a) is a grid of heights and Figure I.1(b) is the two views of that grid. Figure I.2 is what remains after removing as many boxes as possible from Figure I.1(a). Each number in a figure is the number of boxes stacked in that cell.

Figure I.1. (a) Grid of heights and (b) the corresponding views.

Figure I.2. Grid of heights after removing boxes.

Write a program that computes the maximum number of boxes that can be removed without changing the original front view and side view.

Input

The first line contains the number of rows nn and the number of columns mm, separated by a space (1n,m10001 \le n, m \le 1000).

Each of the next nn lines contains the mm heights of one row. Every height is an integer between 00 and 10000000001\,000\,000\,000, and the n×mn \times m heights in the grid are all different.

Output

Print one line with the maximum number of boxes that can be removed without changing the original views.