Under construction

Still being built. Things may change

Turning Knobs

Interview

Time limit1sMemory limit1024 MB

Summary
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 NN given angles in order. Initially the knob is at angle A0A_0. Jungyeom must turn the knob as needed to set its angle in order to A1A_1, A2A_2, A3A_3, ..., ANA_N.

For example, let A0=180A_0 = 180, A1=270A_1 = 270, and A2=135A_2 = 135. 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 A0=180A_0 = 180, A1=270A_1 = 270, and A2=135A_2 = 135 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 NN, the number of knob angles Jungyeom must set. (1≤N≤1001 \le N \le 100)

The second line gives the initial angle of the knob A0A_0. (0≤A0≤3590 \le A_0 \le 359)

The next NN lines give the knob angles Jungyeom must set, A1A_1, A2A_2, ..., ANA_N, one per line. (0≤Ai≤3590 \le A_i \le 359, 1≤i≤N1 \le i \le N)

Output

Print the sum of the degrees Jungyeom must turn when he turns the knob the minimum amount.

Examples1

  1. Example 1

    Input
    2
    180
    270
    135
    
    Expected output
    225