Clock
Time limit2sMemory limit128 MB
Given hands rotating at nested integer-ratio speeds, choose how much to turn each hand (dragging slower ones) to move from one timestamp to another minimizing total handle travel, output the exact minimal distance as a reduced fraction.
- Level
Medium7 of 10
- Topics
- Math, Greedy, Number theory
- Solved
- No attempts yet
Problem
A celebrated architect is designing a monumental clock that displays the time elapsed since the beginning of the universe.
The clock has hands that turn at constant speeds, numbered from to , fastest to slowest. Hand completes one full revolution every minute ( seconds). Each hand turns slower than the one before it: while hand makes full revolutions, hand makes exactly one.
To set the clock you grab a hand by the handle at its tip and turn it either way. Turning a hand drags every slower hand along in proportion to its usual speed, while every faster hand stays still. The hands are enormous, so the effort spent equals the total distance travelled by the handles you grab.
Consider three hands — a second hand, a minute hand, and an hour hand of lengths , , and meters. To set the clock from 2:30 to 6:00 (see the figure) the cheapest way is to turn the minute hand clockwise and then the hour hand clockwise; the handles travel a total of about meters.

Setting the clock from 2:30 to 6:00.
Find a way to set the clock that minimizes the total distance the handles travel.
Input
The first line contains one integer — the number of hands ().
The second line contains integers (); when this line is empty.
The third line contains integers () — the lengths of the hands.
The next two lines each contain one non-negative integer: the time the clock currently shows and the time it must be set to. Both times are measured in seconds and are less than .
Output
Turning a hand of length through one full revolution moves its handle a distance of , so the minimal total distance is always for a rational number — the sum, over all hands, of a hand's length multiplied by the number of revolutions it is turned.
Output as a reduced fraction p/q with and (print 0/1 when no hand has to move).
In the example above the minimal distance is , so the answer is 10/1.