CF BUDDY
← Problems·

1648A · Weird Sum

1400 · combinatorics, data structures, geometry

Problem: Egor has a table of size n×mn \times m, with lines numbered from 11 to nn and columns numbered from 11 to mm. Each cell has a color that can be presented as an integer from 11 to 10510^5.

Let us denote the cell that lies in the intersection of the rr-th row and the cc-th column as (r,c)(r, c). We define the manhattan distance between two cells (r1,c1)(r_1, c_1) and (r2,c2)(r_2, c_2) as the length of a shortest path between them where each consecutive cells in the path must have a common side. The path can go through cells of any color. For example, in the table 3×43 \times 4 the manhattan distance between (1,2)(1, 2) and (3,3)(3, 3) is 33, one of the shortest paths is the following: (1,2)(2,2)(2,3)(3,3)(1, 2) \to (2, 2) \to (2, 3) \to (3, 3).

Egor decided to calculate the sum of manhattan distances between each pair of cells of the same color. Help him to calculate this sum.

Input Format: The first line contains two integers nn and mm (1nm1 \leq n \le m, nm100000n \cdot m \leq 100\,000) — number of rows and columns in the table.

Each of next nn lines describes a row of the table. The ii-th line contains mm integers ci1,ci2,,cimc_{i1}, c_{i2}, \ldots, c_{im} (1cij1000001 \le c_{ij} \le 100\,000) — colors of cells in the ii-th row.

Output Format: Print one integer — the the sum of manhattan distances between each pair of cells of the same color.

Note: In the first sample there are three pairs of cells of same color: in cells (1,1)(1, 1) and (2,3)(2, 3), in cells (1,2)(1, 2) and (2,2)(2, 2), in cells (1,3)(1, 3) and (2,1)(2, 1). The manhattan distances between them are 33, 11 and 33, the sum is 77.

Sample Cases

Case 1

Input

2 3
1 2 3
3 2 1

Output

7

Case 2

Input

3 4
1 1 2 2
2 1 1 2
2 2 1 1

Output

76

Case 3

Input

4 4
1 1 2 3
2 1 1 2
3 1 2 1
1 1 2 1

Output

129

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback