QOJ.ac

QOJ

시간 제한: 2 s 메모리 제한: 1024 MB 총점: 100 해킹 가능 ✓

#16890. 数列魔法

통계

Hanbyeol 为了迎接时隔三年举办的 UCPC 线下决赛,策划了一个特别的活动。那就是和参赛者们一起分享树莓派!Hanbyeol 将圆柱形的派等分为 $M$ 块,使得每一块的底面都是扇形,并在每一块上放置了一颗树莓。然后,他按顺时针顺序给每一块派从 $1$ 到 $M$ 进行了编号。

Hanbyeol 听说共有 $N$ ($N \le M$) 名参赛者参加比赛,并预先决定了要给每位参赛者分配哪一块派。当所有参赛者到达赛场,Hanbyeol 正准备按计划分发派时,一名参赛者指着派上的一颗树莓宣布:“如果不把那颗树莓给我,我就在 10 分钟内把题目全做出来!”随后,其他参赛者也开始一个接一个地说出自己想要的树莓,最终所有参赛者都说出了自己想吃的树莓。

为了满足参赛者的要求,Hanbyeol 打算调整派上树莓的位置。然而,这些树莓对环境变化非常敏感,如果不按照以下方法移动,它们很快就会变质。

  • 选择一块派,将其上所有的树莓移动到紧邻的下一块派上。

这里,第 $1$ 块派的下一块是第 $2$ 块,第 $2$ 块的下一块是第 $3$ 块,……,第 $M-1$ 块的下一块是第 $M$ 块,第 $M$ 块的下一块是第 $1$ 块。

由于树莓变质会影响其他树莓,Hanbyeol 希望在保证没有任何树莓变质的前提下,通过最少的移动次数来满足所有参赛者的要求。为了防止比赛在 10 分钟内就结束的惨剧,请帮帮 Hanbyeol。

注意,参赛者并不介意是否会和自己想要的树莓以外的其他树莓一起吃,且在移动树莓时,即使选择了一块有多个树莓的派,移动次数也只计为一次。

输入格式

第一行包含派的块数 $M$ 和参赛者人数 $N$,以空格分隔。($1 \le N \le M \le 300\,000$)

第二行包含 $N$ 个整数 $a_1, \dots, a_N$,以空格分隔。($1 \le a_i \le M$) $a_i$ 表示分配给第 $i$ 位参赛者的派的编号,所有 $a_i$ 互不相同。

第三行包含 $N$ 个整数 $b_1, \dots, b_N$,以空格分隔。($1 \le b_i \le M$) $b_i$ 表示第 $i$ 位参赛者想要的树莓所在的派的编号。

输出格式

如果能在不使树莓变质的情况下满足所有参赛者的要求,输出移动树莓次数的最小值。否则,输出 $-1$。

样例

输入 1

5 2
3 5
1 4

输出 1

3

输入 2

3 2
3 2
1 2

输出 2

5

输入 3

4 3
1 3 4
1 1 3

输出 3

-1

说明

在第一个样例中,可以通过以下方法移动树莓共 $3$ 次来满足所有参赛者的要求。没有比这更少的移动方法了。

i. 将第 $1$ 块派上的所有树莓移动到第 $2$ 块。 ii. 将第 $2$ 块派上的所有树莓移动到第 $3$ 块。 iii. 将第 $4$ 块派上的所有树莓移动到第 $5$ 块。

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.