PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#FT0000076. Sắp xếp chỗ ngồi – Bản khó (Seating Arrangements (Hard Version))

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Sắp xếp chỗ ngồi – Bản khó (Seating Arrangements (Hard Version))

Seating Arrangements (Hard Version)

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

A cinema has nn rows, each with mm seats. Seats are numbered left to right and then row by row: row rr has seat numbers (r−1)m+1(r-1)m+1 through rmrm. Smaller seat numbers provide a better view.

Exactly nmnm spectators arrive in order 1,2,…,nm1,2,\ldots,nm. Spectator ii has eyesight level aia_i and must receive one unique seat. An assignment is valid only if ai<aja_i<a_j implies that the seat number of spectator ii is smaller than that of spectator jj. Spectators with equal eyesight may be arranged arbitrarily among the corresponding seats.

When entering, each spectator walks along their assigned row from the left to their seat. Their inconvenience equals the number of already-occupied seats strictly to the left of theirs in the same row; empty seats do not count.

Minimize the sum of inconveniences over all valid seat assignments.

Input

The first line contains integers n,mn,m, the number of rows and seats per row.

The second line contains exactly nmnm integers a1,a2,…,anma_1,a_2,\ldots,a_{nm}, the eyesight levels in arrival order.

Output

Print one integer: the minimum total inconvenience across all spectators.

Subtasks

  • Subtask 1 (20 points): 1≤n,m≤41\le n,m\le 4; 1≤ai≤1091\le a_i\le 10^9 for all 1≤i≤nm1\le i\le nm; nm≤105nm\le 10^5.

  • Subtask 2 (30 points): 1≤n,m≤401\le n,m\le 40; 1≤ai≤1091\le a_i\le 10^9 for all 1≤i≤nm1\le i\le nm; nm≤105nm\le 10^5.

  • Subtask 3 (50 points): 1≤n,m≤3001\le n,m\le 300; 1≤ai≤1091\le a_i\le 10^9 for all 1≤i≤nm1\le i\le nm; nm≤105nm\le 10^5.

Examples

Input

2 2
1 1 2 1

Output

0

Explanation

There are two rows with two seats each, and eyesight levels [1,1,2,1][1,1,2,1]. The three spectators with level 11 must occupy seats 1,2,31,2,3, while spectator 33 with level 22 receives seat 44.

Assign seats 2,1,4,32,1,4,3 to spectators 1,2,3,41,2,3,4 respectively.

  • Spectator 11 finds the first row empty: inconvenience 00.
  • Spectator 22 goes to seat 11, with no seat to its left: 00.
  • Spectator 33 finds the second row empty upon taking seat 44: 00.
  • Spectator 44 goes to seat 33, the leftmost seat in row two: 00.

The total is 00, which is minimal because inconvenience is nonnegative. Print 0.