7_13_G题 Median(二分)

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值