Problem Description
寒假的时候,ACBOY要去拜访很多朋友,恰巧他所有朋友的家都处在坐标平面的X轴上。ACBOY可以任意选择一个朋友的家开始访问,但是每次访问后他都必须回到出发点,然后才能去访问下一个朋友。
比如有4个朋友,对应的X轴坐标分别为1, 2, 3, 4。当ACBOY选择坐标为2的点做为出发点时,则他最终需要的时间为 |1-2|+|2-2|+|3-2|+|4-2| = 4。
现在给出N个朋友的坐标,那么ACBOY应该怎么走才会花费时间最少呢?
比如有4个朋友,对应的X轴坐标分别为1, 2, 3, 4。当ACBOY选择坐标为2的点做为出发点时,则他最终需要的时间为 |1-2|+|2-2|+|3-2|+|4-2| = 4。
现在给出N个朋友的坐标,那么ACBOY应该怎么走才会花费时间最少呢?
Input
输入首先是一个正整数M,表示M个测试实例。每个实例的输入有2行,首先是一个正整数N(N <= 500),表示有N个朋友,下一行是N个正整数,表示具体的坐标(所有数据均<=10000).
Output
对于每一个测试实例,请输出访问完所有朋友所花的最少时间,每个实例的输出占一行。
Sample Input
2
2
2 4
3
2 4 6
Sample Output
2
4
解:
假设这是一个坐标轴,我们在圆的位置,左边两个点,右边三个点,当我们往左走一格时(假设没有跨过任何点),距离右边的三个点都远了一格,二距离左边的两个点有近了一格,简单的到我们往点多的一侧移动即可减少距离和,知道我们两侧的点数相等时,这就是中位数。
#include <algorithm> #include <iostream> #include <cstring> #include <cstdio> #include <vector> #include <cmath> #include <queue> #include <deque> #include <cmath> #include <map> using namespace std; typedef long long ll; const double inf=1e20; const int maxn=1e5+10; const int mod=1e9+7; int a[maxn]; int main(){ int t; scanf("%d",&t); while(t--){ int n; scanf("%d",&n); for(int i=0;i<n;i++){ scanf("%d",&a[i]); } sort(a,a+n); int m=(n)/2; int num=0; for(int i=0;i<n;i++){ if(i<m)num+=a[m]-a[i]; else num+=a[i]-a[m]; } printf("%d\n",num); } return 0; }