#B4239. Minimal Travel Distance

    ID: 11896 Type: Default 1000ms 256MiB

Minimal Travel Distance

Minimal Travel Distance

TaoTao has \(n\) good friends whose houses are located along a straight street. Consider the street as a number line with an origin \(0\), and the houses are located at coordinates \(x_1, x_2, \dots, x_n\). TaoTao starts at coordinate \(x_0\) and wants to visit at least \(n-1\) friends. Determine the minimum total distance TaoTao must travel.

The optimal strategy is to choose a segment among the friends' houses such that the required travel distance is minimized. If all friends are visited, the minimum distance is given by:

[ \text{cost}{all} = (x{max} - x_{min}) + \min(|x_0 - x_{min}|, |x_{max} - x_0|) ]

However, since visiting at least \(n-1\) friends is enough, TaoTao may choose to skip one friend. There are two possible segments to consider:

  • Skip the leftmost friend: cover houses from \(x_2\) to \(x_n\), so the cost is \[ \text{cost}_{skip-left} = (x_n - x_2) + \min(|x_0 - x_2|, |x_n - x_0|) \]
  • Skip the rightmost friend: cover houses from \(x_1\) to \(x_{n-1}\), so the cost is \[ \text{cost}_{skip-right} = (x_{n-1} - x_1) + \min(|x_0 - x_1|, |x_{n-1} - x_0|) \]

If \(n = 1\), TaoTao doesn't need to travel because visiting \(n-1 = 0\) friends requires no walk.

Your task is to output the minimal total travel distance based on the above strategy.

inputFormat

The first line contains two integers \(n\) and \(x_0\) (the number of friends and TaoTao's starting coordinate).

The second line contains \(n\) space-separated integers \(x_1, x_2, \dots, x_n\) representing the coordinates of the friends' houses.

outputFormat

Output a single integer representing the minimal total distance that TaoTao must travel.

sample

3 10
1 7 12
7