Codeforces 709B 模拟

B. Checkpoints
time limit per test:1 second
memory limit per test:256 megabytes
input:standard input
output:standard output

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.

Examples
Input
3 10
1 7 12
Output
7
Input
2 0
11 -10
Output
10
Input
5 0
0 0 1000 0 0
Output
0
Note

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个标记最少需要的路程。
思路:模拟。路程最少,所以只需要经过n-1个点。a的右边经过cou个点,则坐标经过n-1-cou个点。
代码:
#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;
}
View Code
I am a slow walker,but I never walk backwards.
原文地址:https://www.cnblogs.com/GeekZRF/p/5866133.html