ACM_Checkpoints-模拟、排序、

来源:互联网 发布:印度冷战作用知乎 编辑:程序博客网 时间:2024/06/17 21:13
E - Checkpoints
Time Limit:1000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u
Submit Status Practice CodeForces 709B

Description

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.

Input

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.

Output

Print one integer — the minimum distance Vasya has to travel in order to visit at least n - 1 checkpoint.

Sample Input

Input
3 101 7 12
Output
7
Input
2 011 -10
Output
10
Input
5 00 0 1000 0 0
Output
0

Hint


题意不说了,把一些关键词翻译出来,就基本能知道意思了,另外,本题还需要考虑一种情况,就是n==1的情况,应输出0;本人就是在这里错误,花费了一些时间。本题要考虑最优的情况,它要求最短,所以从当前位置到最右或者最左,看哪种最短,舍弃最长的那个点,然后在具体比较剩下的最左和最右位置,取最短为优,具体看代码。。。

#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
int x[1000000];
int main(){
int n,a,sh=0,shortleft,shortright;
cin>>n>>a;
for(int i=0;i<n;i++){
      cin>>x[i];
    }
if(n==1)
{
    sh=0;
}
//将数组由小到大排序
else{
sort(x,x+n);
//模拟所有情况
//舍弃最右边的数
shortleft=min(abs(a-x[0])+abs(x[n-2]-x[0]),abs(a-x[n-2])+abs(x[n-2]-x[0]));
//舍弃最左边的数
shortright=min(abs(a-x[1])+abs(x[n-1]-x[1]),abs(a-x[n-1])+abs(x[n-1]-x[1]));
//求最短的
sh=min(shortleft,shortright);
}
cout<<sh<<endl;
return 0;
}


0 0
原创粉丝点击