Optimal Point on a Line
You are given n points on a line with their coordinates xi. Find the point x so the sum of distances to the given points is minimal.
Input
The first line contains integer n (1 ≤ n ≤ 3·105) — the number of points on the line.
The second line contains n integers xi ( - 109 ≤ xi ≤ 109) — the coordinates of the given n points.
Output
Print the only integer x — the position of the optimal point on the line. If there are several optimal points print the position of the leftmost one. It is guaranteed that the answer is always the integer.
Example
Input
4
1 2 3 4
Output
2
题意:
给出N个点所在数轴的位置,找一个点,使其他点到这个点的距离和最小
思路:
找中位数,就可以了
AC代码:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # include <bits/stdc++.h> 2 using namespace std; 3 typedef long long int ll; 4 const int MAX = 3 * 1e5 + 1; 5 ll a[MAX]; 6 int main() 7 { 8 ll n; 9 scanf("%I64d", &n); 10 ll sum = 0; 11 for(int i = 1; i <= n; i++) 12 { 13 scanf("%I64d", &a[i]); 14 sum += a[i]; 15 } 16 17 sort(a + 1, a + n + 1); 18 if(n % 2) 19 cout << a[n / 2 + 1] << endl; 20 else 21 cout << a[n / 2] << endl; 22 return 0; 23 }