Revenge of the ants 2
Time limit5sMemory limit256 MB
Labeled ants walk both ways on a circular rail and bounce on collision; compute when each ant is back at its start with its initial direction.
- Level
Hard8 of 10
- Topics
- String matching, Sorting, Number theory, Math
- Solved
- No attempts yet
Problem
A circular rail has circumference . Gyeonggeun split the rail into equal parts and numbered the points from to in the clockwise direction. He picked some of those points and placed ants that walk clockwise and ants that walk counterclockwise. No point holds two or more ants.
Every ant on the rail moves a distance of 1 per second. The rail is narrow enough that only one ant fits across it, so when two ants moving in opposite directions meet at a point, both reverse direction at that instant. An ant is a point with no size, so two ants collide only when their positions become exactly equal.
Gyeonggeun tells all the ants apart. Write a program that finds the minimum number of seconds until every ant is back at its starting point and moving in its starting direction.
Input
The first line has the circumference of the rail, the number of ants that walk clockwise, and the number of ants that walk counterclockwise, separated by spaces. (, , , )
The second line has the points that hold the clockwise ants, separated by spaces.
The third line has the points that hold the counterclockwise ants, separated by spaces.
Every point is an integer between and , and the given points are distinct. The points are not necessarily sorted.
Output
Print the minimum time in seconds until every ant is back at its starting point and moving in its starting direction.
Note
In the first example the two ants collide at 0.5 seconds and at 1.5 seconds, and at 2 seconds the state matches the start.