QOJ.ac

QOJ

Time Limit: 1 s Memory Limit: 2048 MB Total points: 100

#7956. Walk Swapping

统计

一个具有 $n$ 个顶点的环 $C$ 是一个图,其中顶点 $i$ 和 $i+1$(对于 $i=1, \dots, n-1$)之间由一条边相连,顶点 $n$ 和 $1$ 之间也由一条边相连,环 $C$ 的顶点编号为 $1$ 到 $n$。

现有 $n$ 枚硬币,每枚硬币的编号均为 $\{1, 2, \dots, n\}$ 中的一个,不同硬币的编号可以相同。初始时,$C$ 的每个顶点上都有一枚硬币。之后,两个顶点可以交换它们上面的硬币。对于 $C$ 中的一条路径 $w = (v_1, v_2, \dots, v_k)$,路径交换是指按照 $i = 1, 2, \dots, k-1$ 的顺序,依次交换 $v_i$ 和 $v_{i+1}$ 上的硬币。这里,路径 $w$ 是一个包含 $k (\ge 1)$ 个顶点的序列,其中相邻的两个顶点不同且在 $C$ 中相邻,它可以被视为遍历 $C$ 时访问的顶点序列。此外,$k$ 被称为 $w$ 的长度。对于长度为 $k \ge 2$ 的路径,路径交换会进行 $k-1$ 次交换;对于长度为 1 的路径,则不进行任何交换。下图展示了在 4 个顶点的环中,路径 $(2, 1, 4, 1)$ 进行路径交换的过程。

给定硬币的初始配置和最终配置,你需要找到一种路径交换方式,使得初始配置变为最终配置,并最小化路径交换中硬币交换的总次数。

例如,在上图中,路径 $(2, 1, 4, 1)$ 的路径交换共进行了 3 次硬币交换,但通过路径 $(1, 2)$ 的路径交换仅需 1 次交换即可达到相同的最终配置。

给定环 $C$ 的顶点数以及顶点上硬币的初始和最终配置,编写一个程序,输出通过路径交换将初始配置变为最终配置所需的最少硬币交换次数。

输入格式

程序从标准输入读取数据。输入的第一行包含一个整数 $n$ ($1 \le n \le 3,000$),表示环 $C$ 的顶点数。顶点编号为 $1$ 到 $n$,硬币编号为 $\{1, 2, \dots, n\}$ 中的整数。第二行包含 $n$ 个整数(允许重复),范围在 $1$ 到 $n$ 之间,其中第 $i$ 个整数表示初始配置中位于顶点 $i$ 上的硬币编号,对于 $i = 1, \dots, n$。第三行包含 $n$ 个整数(允许重复),范围在 $1$ 到 $n$ 之间,其中第 $i$ 个整数表示最终配置中位于顶点 $i$ 上的硬币编号,对于 $i = 1, \dots, n$。

输出格式

程序向标准输出写入数据。仅打印一行,包含将初始配置变为最终配置的路径交换中所需的最少硬币交换次数。如果不存在这样的路径交换,即无法通过任何路径交换达到最终配置,则输出 -1。

样例

输入 1

4
4 3 2 1
3 4 2 1

输出 1

1

输入 2

6
2 1 1 2 2 1
1 2 2 2 1 1

输出 2

7

输入 3

6
4 1 3 6 2 5
6 2 1 3 4 5

输出 3

-1

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.