Description
Given N numbers, X1, X2, ... , XN, let us calculate the difference of every pair of numbers: ∣Xi - Xj∣ ( ≤ i < j ≤ N). We can get C(N,) 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/)-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 = .
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 ≤ ,,, ≤ N ≤ ,, )
Output
For each test case, output the median in a separate line.
Sample Input
Sample Output
Source
这道题直接暴力枚举肯定是超时。
可以采用二分枚举一个数mid。对a数组排序后,与a_i的差大于mid(也就是某个数大于X_i + mid)的那些数的个数如果小于N / 2的话,说明mid太大了。以此为条件进行第一重二分搜索,第二重二分搜索是对a的搜索,直接用lower_bound实现。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<math.h>
#include<stdlib.h>
using namespace std;
#define N 100006
int n,m;
int a[N];
bool solve(int mid){
int cnt=;
for(int i=;i<n;i++){
int tmp=n-(lower_bound(a,a+n,a[i]+mid)-a);//a[i]加上mid看看有多少个
cnt+=tmp;
}
if(cnt>m) return true;//如果太多,则要调整mid向上,>还是>=有时候要调整
return false;
}
int main()
{
while(scanf("%d",&n)==){
m=n*(n-)/;
for(int i=;i<n;i++){
scanf("%d",&a[i]);
}
sort(a,a+n);
int low=;
int high=a[n-]-a[];
while(low<high){
int mid=(low+high)>>;
if(solve(mid)){
low=mid+;
}
else{
high=mid;
}
}
printf("%d\n",low-);//有时要调整,减1或不减
}
return ;
}