Turning Knobs
InterviewTime limit1sMemory limit1024 MB
Starting from angle A0, find the total degrees turned when moving through angles A1..AN, each step choosing the shorter of the two rotation directions on a 360-degree circle.
- Level
Easy3 of 10
- Topics
- Implementation, Math, Greedy, Simulation
- Solved
- No attempts yet
Problem
Jungyeom likes to play games at the arcade. His favorite game is the one where you have to turn a knob precisely.

A knob is a device you operate by turning it left or right. It is commonly used to adjust volume. If you have trouble picturing how a knob turns, you can imagine a car steering wheel that spins freely with no stops.
How far the knob has turned can be expressed by the angle it currently sits at. The angle of the knob is an integer from 0 degrees to 359 degrees. Starting at 0 degrees and turning the knob right by 1 degree at a time, the angle goes 1, 2, 3, ... 358, 359, and then back to 0 degrees. Conversely, turning the knob left by 1 degree at a time changes the angle as 359, 358, and so on.
Jungyeom wanted to turn the knob as well as Taesu, the arcade's top player, but could not. So he decided to have you write a program that lets him turn the knob well. Jungyeom must set the knob to given angles in order. Initially the knob is at angle . Jungyeom must turn the knob as needed to set its angle in order to , , , ..., .
For example, let , , and . Jungyeom can turn the knob from 180 degrees right by 90 degrees to reach 270 degrees. Then he can turn it right by another 225 degrees to reach 135 degrees. In this case he has turned the knob 315 degrees in total.
Jungyeom thinks he should turn the knob as little as possible to turn it well. So when he turns the knob the minimum amount, he wants to know the total number of degrees he must turn.
For example, let , , and as above. Jungyeom can turn the knob from 180 degrees right by 90 degrees to reach 270 degrees. Then, instead of turning right, he can turn it left by 135 degrees to reach 135 degrees. In this case he has turned the knob 225 degrees in total. For this example there is no way to place the knob at the given angles in order with less turning.
Input
The first line gives , the number of knob angles Jungyeom must set. ()
The second line gives the initial angle of the knob . ()
The next lines give the knob angles Jungyeom must set, , , ..., , one per line. (, )
Output
Print the sum of the degrees Jungyeom must turn when he turns the knob the minimum amount.