QOJ.ac

QOJ

時間限制: 5.0 s 記憶體限制: 1024 MB 總分: 100

#7552. 硬币游戏

统计

长度为 $n$ 的环 $C$ 是一个顶点编号为 $1$ 到 $n$ 的图,其中对于每个 $i = 1, \dots, n$,顶点 $i$ 与顶点 $(i \pmod n + 1)$ 之间有一条边相连。

考虑放置在环上的 $n$ 枚硬币,使得每个顶点包含一枚硬币。每枚硬币上都有一个 $1$ 到 $n$ 之间的数字,但某些数字可能相同。我们从某个顶点出发,沿着边行走,并在过程中交换硬币。长度为 $k \ge 1$ 的交换路径 $w = (v_1, v_2, \dots, v_k)$ 会进行 $k - 1$ 次交换:对于 $i = 1, 2, \dots, k - 1$,按此顺序交换顶点 $v_i$ 和 $v_{i+1}$ 上的两枚硬币。交换路径中任意两个连续的顶点在 $C$ 中必须相邻。

下图展示了在具有 4 个顶点的环中,交换路径 $(2, 1, 4, 1)$ 的过程:

给定两种硬币配置,即初始配置和最终配置:对于 $C$ 中的每个顶点,给出最初位于该顶点的硬币,以及最终应该位于该顶点的硬币。求出将初始配置转换为最终配置的最小长度的交换路径,或者确定不存在这样的交换路径。

例如,在上图中,交换路径 $(2, 1, 4, 1)$ 的长度为 $3$。然而,最终配置也可以通过长度为 $1$ 的交换路径 $(1, 2)$ 实现。

输入格式

输入的第一行包含一个整数 $n$ ($1 \le n \le 3000$),表示环 $C$ 的长度。

第二行包含 $n$ 个 $1$ 到 $n$ 之间的整数(不一定互不相同):最初放置在顶点 $1, 2, \dots, n$ 上的硬币数字。

第三行包含 $n$ 个 $1$ 到 $n$ 之间的整数(不一定互不相同):最终要求位于顶点 $1, 2, \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.