QOJ.ac

QOJ

実行時間制限: 2 s メモリ制限: 64 MB 満点: 100
統計

一家公司经营着 $N$ 家商店,每家商店销售 $M$ 种不同的产品。公司有一个大型仓库,产品在运往商店前会先在这里打包。每家商店收到的每种产品的数量相同。因此,公司将一定数量的某种产品装入一个容器,并用产品标识符标记该容器。产品标识符为 $1$ 到 $M$ 的数字。因此,打包完成后,仓库中共有 $N \times M$ 个容器,且每种产品都有 $N$ 个容器贴有该产品的标签。由于仓库位于一栋狭窄的建筑物内,容器被排成一行。为了加快配送速度,仓库经理想要重新排列这些容器。由于产品配送到商店的方式是每家商店派出一辆卡车,且每辆卡车携带每种产品各一个容器,因此一种合适的排列方式如下:行中的前 $M$ 个容器必须贴有不同的产品标签,接下来的 $M$ 个容器也必须贴有不同的产品标签,依此类推。遗憾的是,行尾只有一个空位可以放置容器。因此,重新排列必须通过连续拾取一个容器并将其移动到空位来完成。重新排列后,空位必须位于行尾。

目标是通过最少的移动次数实现所需的重新排列。

任务

你需要编写一个程序,计算出实现所需重新排列的最少移动次数。

输入格式

输入文件的第一行包含两个整数 $N$ 和 $M$。$N$ ($1 \le N \le 400$) 是商店的数量,$M$ ($1 \le M \le 400$) 是产品的数量。第二行包含 $N \times M$ 个整数,即容器初始顺序的标签。每个产品标识符 $x$ ($1 \le x \le M$) 在该行中恰好出现 $N$ 次。

输出格式

输出文件的第一行包含一个整数 $S$,即获得所需容器行顺序所需的最少移动次数(子任务 A)。接下来的 $S$ 行描述了一种重新排列方案(子任务 B)。每行包含一对整数 $x$ $y$。这对整数 $x$ $y$ 描述了一次移动:将位于位置 $x$ 的容器移动到位置 $y$。位置由 $1$ 到 $N \times M + 1$ 的数字标识;初始时位置 $N \times M + 1$ 是空的(没有容器)。只有当位置 $y$ 在移动前为空时,从 $x$ 到 $y$ 的移动才是合法的。从 $x$ 移动到 $y$ 后,位置 $x$ 将变为空。如果你只解决子任务 A,则只需输出第一行。

如果存在多种可能性,你的程序只需输出其中一种;输出哪一种均可。

样例

样例输入 1

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

样例输出 1

8
9 31
18 9
10 18
4 10
31 4
30 31
24 30
31 24

Discussions

About Discussions

The discussion section is only for posting: General Discussions (problem-solving strategies, alternative approaches), and Off-topic conversations.

This is NOT for reporting issues! If you want to report bugs or errors, please use the Issues section below.

Open Discussions 0
No discussions in this category.

Issues

About Issues

If you find any issues with the problem (statement, scoring, time/memory limits, test cases, etc.), you may submit an issue here. A problem moderator will review your issue.

Guidelines:

  1. This is not a place to publish discussions, editorials, or requests to debug your code. Issues are only visible to you and problem moderators.
  2. Do not submit duplicated issues.
  3. Issues must be filed in English or Chinese only.
Active Issues 0
No issues in this category.
Closed/Resolved Issues 0
No issues in this category.