QOJ.ac

QOJ

時間限制: 4.0 s 記憶體限制: 512 MB 總分: 100 可 Hack ✓

#18147. 变为非递减的漫长之路

统计

小 R 是一位喜欢非降(单调不减)数组的魔法师。她有一个长度为 $n$ 的数组,初始为 $a_1, \dots, a_n$,其中每个元素都是 $[1, m]$ 范围内的整数。她希望将其变为非降的,即 $a_1 \le a_2 \le \dots \le a_n$。

为此,她可以进行若干次魔法。小 R 有一个长度为 $m$ 的固定数组 $b_1, \dots, b_m$。形式上,我们将一次魔法定义为按顺序执行以下操作的过程:

  • 选择一个集合 $S \subseteq \{1, 2, \dots, n\}$。
  • 对于每个 $u \in S$,将 $a_u$ 赋值为 $b_{a_u}$。

小 R 想知道最少需要多少次魔法才能使初始数组变为非降的。如果无论进行多少次魔法都无法实现,则输出 $-1$。

输入格式

每个测试点包含多个测试用例。第一行包含测试用例的数量 $t$ ($1 \le t \le 10^4$)。

接下来是测试用例的描述。

每个测试用例的第一行包含两个整数 $n$ 和 $m$ ($1 \le n \le 10^6$, $1 \le m \le 10^6$) —— 初始数组的长度和数组中元素的范围。

每个测试用例的第二行包含 $n$ 个整数 $a_1, \dots, a_n$ ($1 \le a_i \le m$) —— 初始数组。

每个测试用例的第三行包含 $m$ 个整数 $b_1, \dots, b_m$ ($1 \le b_i \le m$) —— 固定的魔法数组。

保证所有测试用例中 $n$ 的总和不超过 $10^6$,且所有测试用例中 $m$ 的总和不超过 $10^6$。

输出格式

对于每个测试用例,输出一个整数:使 $a_1, \dots, a_n$ 变为非降所需的最少魔法次数,如果无法实现则输出 $-1$。

样例

输入样例 1

3
5 8
1 6 3 7 1
2 3 5 8 7 1 5 6
3 3
1 3 2
2 1 3
10 10
2 8 5 4 8 4 1 5 10 10
6 7 2 6 3 4 1 1 3 5

输出样例 1

3
-1
3

说明

在第一个测试用例中,初始数组 $a_1, \dots, a_n$ 为 $[1, 6, 3, 7, 1]$。你可以按如下方式选择 $S$:

  • 第一次魔法:$S = [2, 4, 5]$,$a = [1, 1, 3, 5, 2]$;
  • 第二次魔法:$S = [5]$,$a = [1, 1, 3, 5, 3]$;
  • 第三次魔法:$S = [5]$,$a = [1, 1, 3, 5, 5]$。

因此,可以通过 $3$ 次魔法使 $a_1, \dots, a_n$ 变为非降。可以证明这是所需的最少魔法次数。

在第二个测试用例中,无法使 $a_1, \dots, a_n$ 变为非降。

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.