Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order.
Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value.
The first line of the input contains two integers n and a (1 ≤ n ≤ 100 000, - 1 000 000 ≤ a ≤ 1 000 000) — the number of checkpoints and Vasya's starting position respectively.
The second line contains n integers x1, x2, ..., xn ( - 1 000 000 ≤ xi ≤ 1 000 000) — coordinates of the checkpoints.
Print one integer — the minimum distance Vasya has to travel in order to visit at least n - 1 checkpoint.
3 10
1 7 12
7
2 0
11 -10
10
5 0
0 0 1000 0 0
0
In the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12 - 10 = 2) and then proceed to the second one (distance is 12 - 7 = 5). The total distance is equal to 2 + 5 = 7.
In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point - 10.
题目连接:http://codeforces.com/contest/709/problem/B
题意:一条直线上面有n个标记,一个起点a。从起点开始出发最少经过n-1个标记最少需要的路程。
#include<iostream> #include<cstdio> #include<algorithm> using namespace std; int x[100100]; int l[100100],r[100100]; int main() { int i,n,a; scanf("%d%d",&n,&a); int cou=0; for(i=1; i<=n; i++) { scanf("%d",&x[i]); if(x[i]<=a) cou++; } int cou1=cou; sort(x+1,x+n+1); for(i=1; i<=n; i++) { if(x[i]<=a) l[cou]=x[i],cou--; else r[++cou]=x[i]; } l[0]=r[0]=a; int cou2=cou; int ans=10000000; for(i=0; i<=cou2; i++) { if(i>n-1) break; if(n-1-i>cou1) continue; int sign; if(i==0) sign=a-l[n-1]; else if(i==n-1) sign=r[n-1]-a; else { if(r[i]-a<=a-l[n-1-i]) sign=r[i]-a+r[i]-l[n-1-i]; else sign=a-l[n-1-i]+r[i]-l[n-1-i]; } if(sign<ans) ans=sign; } cout<<ans<<endl; return 0; }