Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 7293 | Accepted: 2484 |
Description
Given N numbers, X1, X2, ... , XN, let us calculate the difference of every pair of numbers: ∣Xi - Xj∣ (1 ≤ i < j ≤ N). We can get C(N,2) differences through this work, and now your task is to find the median of the differences as quickly as you can!
Note in this problem, the median is defined as the (m/2)-th smallest number if m,the amount of the differences, is even. For example, you have to find the third smallest one in the case of m = 6.
Input
The input consists of several test cases.
In each test case, N will be given in the first line. Then N numbers are given, representing X1, X2, ... , XN, ( Xi ≤ 1,000,000,000 3 ≤ N ≤ 1,00,000 )
Output
For each test case, output the median in a separate line.
Sample Input
4 1 3 2 4 3 1 10 2
Sample Output
1 8
给出一个含有 n 个元素的数列, 求各元素差的中位数。
运用两次二分。
第一次二分枚举中位数 md, 判断依据是小于等于 md 的差的个数。
求小于等于 md 的差的个数时,用到了第二次二分。
给公式:a[j] - a[i] <= md => a[j] <= a[i] + md 。
所以只需要在排好序的 a 数组里用 upper_bound就可以轻易求出 a[i] 为被减数的小于等于 md 的差的个数。然后让 i 遍历 0 - n-1 好了。
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 100100;
const int inf = 0x3f3f3f3f;
int a[maxn];
bool C(int md, int k, int n)
{
int cnt = 0;
//求有多少个 a 中元素两两相减的差 <= md
//枚举 a[i]
//求有多少个j满足 a[j] - a[i] <= md
//a[j] <= a[i] + md
//所以只要二分计数 a 中小于等于 a[i] + md 的个数就可以了
for(int i= 0; i< n; i++){
cnt += upper_bound(a+i+1, a+n, a[i]+md) - a - i - 1;
if(cnt >= k) return true;
}
return false;
}
int main ()
{
int n;
while(~scanf("%d", &n)){
//中值是第几大
int k = (n * (n-1) / 2 + 1) / 2;
for(int i= 0; i< n; i++)
scanf("%d", a+i);
sort(a, a+n);
//二分枚举 答案
int lb = 0, ub = inf;
while(lb <= ub){
int md = (lb + ub) >> 1;
if(C(md, k, n)) ub = md - 1;
else lb = md + 1;
}
printf("%d\n", ub+1);
}
return 0;
}