logo AlgoBeat OnlineJudge
登录 注册

#216581. [ICPC 2026 LAC] Ants on a Ring

内存限制:1024 MiB 时间限制:500 ms 标准输入输出
题目类型:VJudge(洛谷) 评测方式:VJudge
上传者: 匿名

题目描述

There are ants on a circle. The circle has spots numbered from to clockwise, with spot adjacent to spot . Ants start at different spots, and want to reach different spots. To do so, in one second each ant may stay still or move around the circle to an adjacent spot (clockwise or counterclockwise).

No two ants can be at the same position on the circle at the same time, even between spots. For instance, suppose that during a second an ant moves clockwise from spot to spot . During that second, other ants cannot do any of the following:

  • Stay still at spot (ants would meet at spot ).
  • Move counterclockwise from spot to spot (ants would meet at spot ).
  • Move counterclockwise from spot to spot (ants would meet between spots and ).

Determine whether it is possible for all ants to reach their targets, and if so, the minimum number of seconds required. That is, find the minimum such that after seconds, every ant can be at its target spot.

输入格式

The first line contains two integers () and (), indicating respectively the number of ants and the number of spots.

The second line contains different integers ( for ), where is the initial spot of the -th ant.

The third line contains different integers ( for ), such that is the target spot of the -th ant.

输出格式

Output a single line with an integer indicating the minimum time required for all ants to reach their targets, or the character “*” (asterisk) if it is impossible.

样例

样例输入 1

2 2
2 1
2 1

样例输出 1

0

样例输入 2

2 2
1 2
2 1

样例输出 2

1

样例输入 3

1 10
1
7

样例输出 3

4

样例输入 4

3 5
1 3 2
5 2 4

样例输出 4

*

样例输入 5

3 5
1 3 2
4 2 5

样例输出 5

2

数据范围与提示

Explanation of Sample 1:

The two ants start at their target spots, so the answer is .

Explanation of Sample 2:

The two ants can move simultaneously either clockwise or counterclockwise, reaching their targets after just second.

Explanation of Sample 5:

All three ants can move counterclockwise, with the second ant staying still for a second.