CodeForces 709B Checkpoints

分类讨论。

先对$n$个坐标进行排序。如果$a$在$x[1]$左边,那么肯定是$x[n]$不走。如果$a$在$x[n]$右边,那么$x[1]$不走。

剩下的讨论一下是$x[1]$不走还是$x[n]$不走,几种情况都算一下取最小值即可。

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<iostream>
using namespace std;
typedef long long LL;
const double pi=acos(-1.0),eps=1e-6;
void File()
{
    freopen("D:\in.txt","r",stdin);
    freopen("D:\out.txt","w",stdout);
}
template <class T>
inline void read(T &x)
{
    char c = getchar(); x = 0;while(!isdigit(c)) c = getchar();
    while(isdigit(c)) { x = x * 10 + c - '0'; c = getchar();  }
}

LL INF=1e17;
const int maxn=100010;
LL x[maxn],a;
int n;

int main()
{
    scanf("%d%lld",&n,&a);
    for(int i=1;i<=n;i++) scanf("%lld",&x[i]);
    sort(x+1,x+1+n);
    
    if(n==1) {printf("0
");return 0;}
    
    if(x[1]>=a) { printf("%lld
",x[n-1]-a); return 0;}
    if(a>=x[n]) { printf("%lld
",a-x[2]); return 0;}

    LL f1=INF,f2=INF,f3=INF,f4=INF;

    if(x[2]<=a) f1=2*(a-x[2])+(x[n]-a);
    else f1=x[n]-a;

    f2=2*(x[n]-a)+(a-x[2]);

    if(a<=x[n-1]) f3=2*(x[n-1]-a)+(a-x[1]);
    else f3=a-x[1];

    if(x[1]<=a) f4=2*(a-x[1])+(x[n-1]-a);

    printf("%lld
",min(min(f1,f2),min(f3,f4)));

    return 0;
}
原文地址:https://www.cnblogs.com/zufezzt/p/5835691.html