题意:有n个数字,得到所有两两的差值的绝对值,从小到大排列后取中间的数字是多少,如果是偶数个,取中间靠左边的那个数字。
题解:如果是两层for一定会超时,先从小到大排序,用二分枚举差值x,然后计算从i开始往后的序列二分查找大于等于a[i] + x的数字的个数,把所有个数累加起来如果总个数大于n * (n - 1) / 4则继续增大差值,否则减小。
#include <stdio.h>
#include <algorithm>
using namespace std;
const int N = 100005;
int a[N], n, m;
bool judge(int x) {
int cnt = 0;
for (int i = 0; i < n; i++)
cnt += n - (lower_bound(a, a + n, a[i] + x) - a);
return cnt > m ? true : false;
}
int main() {
while (scanf("%d", &n) == 1) {
m = n * (n - 1) / 4;
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
sort(a, a + n);
int l = 0, r = a[n - 1] - a[0];
while (l <= r) {
int mid = (l + r) / 2;
if (judge(mid))
l = mid + 1;
else
r = mid - 1;
}
printf("%d\n", l - 1);
}
return 0;
}