7_13_G题 Median
题意
给出一堆数,要求出他们两两之间差值的中位数是多少
思路
二分中位数,然后去判定这个中位数,判定的方式是看能构成的比这个中位数大的的差值有多少,判定的方法是加上原数列中的数再在原数列中二分找他的位置,可以用STL的函数搞定,如果比他大的差值的数量大于(n*(n-1)/2)/2,则这个中位数小了,否则这个中位数大了,持续二出答案即可。
代码
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 1e5+10;
int n;
int num[maxn];
int cn2 = 0;
bool cheak(int mid){
int cnt = 0;
for(int i = 0 ; i < n ; i ++)
cnt += num+n-lower_bound(num,num+n,num[i]+mid);
if(cnt*2 > cn2) return true;
else return false;
}
int main (){
while(~scanf("%d", &n)){
int l = 1e9+7,r = -(1e9+7);
for(int i = 0 ; i < n ; i ++){
scanf("%d",&num[i]);
r = max(r,num[i]);
l = min(l,num[i]);
}
sort(num,num+n);
cn2 = n*(n-1)/2;
r = r-l;
l = 0;
while(r - l > 1){
int mid = (l+r)>>1;
if(cheak(mid)) l = mid;
else r = mid;
}
printf("%d\n",l);
}
return 0;
}