Depot Rearrangement

Time limit2sMemory limit128 MB

Summary
Find the minimum number of single-item moves through one free slot to rearrange containers so every block of M consecutive positions contains all M distinct products, ending with the free slot restored.
Level

Hard8 of 10

Topics
Graph, Greedy, Combinatorics
Solved
No attempts yet

Problem

A company operates N shops and sells M different products, numbered from 1 to M. In its depot the company packs one container of a product for each shop, so there are exactly N containers labeled with each product and N×M containers in total. Because the depot is narrow, the containers are arranged in a single row at positions 1 through N×M. One extra position, N×M+1, is a single free slot that holds no container.

To speed up distribution, the manager wants to rearrange the row so that each consecutive block of M containers — positions 1..M, then M+1..2M, and so on — is labeled with M distinct products (exactly one container of each product). The order of containers within a block does not matter.

Rearranging is done using only the free slot. A single move takes the container at some occupied position and places it in the position that is currently free; the position it came from then becomes free. After all moves are finished, the free slot must again be at position N×M+1.

Compute the minimum number of moves required.

Input

The first line contains two integers N and M (1 ≤ N ≤ 400, 1 ≤ M ≤ 400). The second line contains N×M integers: the labels of the containers in their initial left-to-right order. Each product label x (1 ≤ x ≤ M) appears exactly N times.

Output

Print a single integer: the minimum number of moves needed so that every consecutive block of M containers holds M distinct product labels and the free slot returns to position N×M+1.

Examples6

  1. Example 1

    Input
    5 6
    4 1 3 1 6 5 2 3 2 3 5 6 2 1 4 5 6 4 1 3 2 4 5 5 1 2 3 4 6 6
    
    Expected output
    8
    
  2. Example 2

    Input
    2 3
    1 2 3 1 2 3
    
    Expected output
    0
    
  3. Example 3

    Input
    1 5
    3 1 5 2 4
    
    Expected output
    0
    
  4. Example 4

    Input
    4 1
    1 1 1 1
    
    Expected output
    0
    
  5. Example 5

    Input
    2 2
    1 1 2 2
    
    Expected output
    3
    
  6. Example 6

    Input
    2 3
    1 1 2 3 3 2
    
    Expected output
    3