计蒜客 | 选址
-
题目
-
思路:
求解得到最后的答案为该组数的中位数。
证明如下:已知,符合该条件的点,一定在该组数的最大值和最小值之间。看数轴上相对点的距离,可得两侧点到中间某点的距离之和,即为两侧点之间的距离。若该点不位于中位数,则会增加该点到中位数的距离,使结果增大,所以最优解为该组数的中位数。 -
代码
#include<iostream>
#include<algorithm>
using namespace std;
#define N 100005
int p[N];
int main()
{
//求中位数
int n;//点数
cin >> n;
int t = 0;//到该点的距离
int tc = 0;
int c;//最后选的点choice
int max = 0, min = 100005;//数轴的两个端点
for (int i = 0; i < n; i++)
{
cin >> p[i];
}
//排序求中位数
sort(p, p + n);
c = n % 2 == 0 ? p[n / 2 - 1] : p[n / 2];
cout << c << endl;
system("pause");
return 0;
}