Skip to main content
Back to problems
Codeforces
Medium
Arrays
Matrices
Sorting
Polo the Penguin and Matrix

Rearrange the numbers in a matrix using the minimum local movement implied by repeated adjacent swaps, and report the required total effort.

Acceptance 0%
Problem Statement

Problem Summary

You are given an n×mn \times m 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 nn and mm.
  • The next nn lines each contain mm integers describing the matrix.

Output Format

  • Print a single integer: the minimum total number of adjacent swaps needed.

Constraints

  • 1n,m1 \le n, m
  • 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 nn and mm.
  • Read an n×mn \times m 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.
Examples
Sample cases returned by the problem API.

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.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.