#P7684. [CEOI 2005] Depot Rearrangement

    ID: 6847 远端评测题 2000ms 64MiB 尝试: 0 已通过: 0 难度: 8 上传者: 标签>图论2005Special JudgeCEOI欧拉回路二分图构造

[CEOI 2005] Depot Rearrangement

Description

A company operates NN stores, and each store sells MM different products. The company has a large depot, where products are packed before being shipped to the stores. Each store will receive the same amount of each product. Therefore, the company packs a certain amount of the same product into one container and marks the container with the product identifier.

Products are identified by the numbers from 11 to MM. Thus, after packing is finished, there will be N×MN×M containers in the depot, and for each product label there are exactly NN containers with that label. Since the depot is located in a narrow building, the containers are placed in a single line.

To speed up deliveries, the depot manager wants to rearrange the containers. Since products are delivered by sending one truck to each store, and each truck carries one container of each product, the desired arrangement is as follows: the first MM containers in the line must have pairwise different product labels, the second MM containers must also have pairwise different product labels, and so on. Unfortunately, there is only one free space at the end of the line, which can hold one container. Therefore, the rearrangement must be done by repeatedly picking up one container and moving it into the free space. After rearrangement, the free space must also be at the end of the line.

The goal is to achieve the required rearrangement using the minimum number of moves. You are asked to write a program to compute the minimum number of moves needed to reach a valid arrangement.

Input Format

The first line contains two integers NN and MM. NN is the number of stores, and MM is the number of products. The second line contains N×MN×M integers, the labels of the containers in their initial order. Each product identifier xx appears exactly NN times in the line.

Output Format

The first line contains an integer SS, the minimum number of moves required to reach a valid arrangement. The next SS lines describe the rearrangement. Each line contains a pair of integers xx, yy. The pair xx, yy describes one move: the container at position xx is moved to position yy.

Positions are numbered from 11 to N×M+1N×M+1; initially, position N×M+1N×M+1 is the free space (it has no container). A move from xx to yy is legal only if position yy is free before the move. After moving from xx to yy, position xx becomes the free space.

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
8
9 31
18 9
10 18 
4 10
31 4
30 31
24 30
31 24

Hint

Constraints

For 100%100\% of the testdata, 1N4001 \leq N \leq 400, 1M4001 \leq M \leq 400, 1xM1 \leq x \leq M.

Notes

From CENTRAL-EUROPEAN OLYMPIAD IN INFORMATICS 2005, Depot Rearrangement.
Translated and organized by

/user/104324

Translated by ChatGPT 5