Rearrange the numbers in a matrix using the minimum local movement implied by repeated adjacent swaps, and report the required total effort.
Problem Summary
You are given an matrix containing integers. By repeatedly swapping adjacent elements in rows and columns, you want to transform the matrix into a state where the values are arranged in nondecreasing order when read row by row.
Your task is to determine the minimum total number of adjacent swaps needed to achieve this arrangement. If the matrix can already be considered sorted in this reading order, the answer is $0$.
Interpretation
Think of the matrix entries as a flattened sequence in row-major order. The goal is to measure how much local movement is needed to place the elements into sorted order.
Input Format
- The first line contains two integers and .
- The next lines each contain integers describing the matrix.
Output Format
- Print a single integer: the minimum total number of adjacent swaps needed.
Constraints
- The matrix contains integers that can be compared and sorted.
- The answer fits in a 64-bit signed integer.
Hints
- Flatten the matrix into a one-dimensional array in row-major order.
- The required number of adjacent swaps is closely related to how far each element must move from its current position to its sorted position.
- Stable handling of equal values can matter when counting movements.
Input Format
- Read integers and .
- Read an grid of integers.
Output Format
- Output one integer: the minimum adjacent-swap effort needed to obtain row-major nondecreasing order.
Constraints
- Values may repeat.
- Use 64-bit arithmetic for the final count.
Example 1
Input
2 3 4 1 3 2 6 5
Output
5
Explanation
Flattening gives [4,1,3,2,6,5]. Sorting to [1,2,3,4,5,6] requires a minimum of 5 adjacent swaps, which equals the inversion count of the flattened sequence when duplicates are handled consistently.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.