Strange sum
InterviewTime limit3sMemory limit1024 MB
Given a grid of colored cells, compute the sum of Manhattan distances over all pairs of cells that share a color.
- Level
Medium5 of 10
- Topics
- Hash map, Sorting, Prefix sum
- Solved
- No attempts yet
Statement
Egor has a table with rows and columns. Rows are numbered 1 to , and columns are numbered 1 to . Each cell is painted with a color, an integer from 1 to .
The cell in row and column is written . The manhattan distance between cells and is the length of the shortest path between them, where consecutive cells share a side. The path may pass through cells of any color. For example, the distance between and is 3, and one shortest path is .
Egor wants the sum of manhattan distances over every pair of cells that have the same color. Compute this sum.
Input
The first line contains two integers and (, ), the number of rows and columns.
Each of the next lines describes one row. The -th line contains integers (), the colors of the cells in row .
Output
Print one integer, the sum of manhattan distances over all pairs of cells with the same color.
Hint
In the first sample, there are three pairs of cells with the same color: and , and , and and . Their manhattan distances are 3, 1, and 3, so the sum is 7.