首页 > 代码库 > Checkpoints codeforces 709B

Checkpoints codeforces 709B

 

http://codeforces.com/problemset/problem/709/B

 

题意:给出一条横向坐标轴,给出Vasya所在的坐标位置及其另外n个坐标。Vasya想要至少访问n-1个位置,问最短所需要走的距离为多少?

 

技术分享
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <algorithm>using namespace std;#define maxn 110000#define INF 1e9+7int a[maxn];int main(){    int n, x;    while(scanf("%d", &n)!=EOF)    {        scanf("%d", &x);        for(int i=0; i<n; i++)            scanf("%d", &a[i]);        sort(a, a+n);        if(n==1)        {            printf("0\n");            continue;        }        if(a[n-1]<=x)//若数组a的元素全部比x小        {            printf("%d\n", x-a[1]);        }        else if(a[0]>=x)//若数组a的元素全部比x大        {            printf("%d\n", a[n-2]-x);        }        else        {            int ans1, ans2;            if(a[n-2]<x)//若数组a的元素有n-1个比x小                ans1=x-a[0];            else                ans1=min(a[n-2]-x, x-a[0])*2+max(a[n-2]-x, x-a[0]);            if(a[1]>x)//若数组a的元素有n-1个比x大                ans2=a[n-1]-x;            else                ans2=min(x-a[1], a[n-1]-x)*2+max(x-a[1], a[n-1]-x);            printf("%d\n", min(ans1, ans2));        }    }    return 0;}
View Code

 

Checkpoints codeforces 709B