POJ 3579

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40924940/article/details/83743997

 本题又是一道二分搜索,不过这次选择了调用函数来搜索数组里具体的某个值,

本题题意:

有 n 个数字 现在想求 每个数字之间的 差 的绝对值的中位数。

可能乍一看有点抽象,首先我们需要知道 n 个数 那么这n个数之间的差的绝对值 共有 C_{n}^{2} 种,那么我需要搜索的就是一个数字它大于等于 这些数中的 中位数 那么我们就成功的逼近了答案。

首先本题中的 lower_bound函数 例如 lower_bound(a,a+n,x)-a 代表返回找到第一个大于 X 的 a[i]的下标

注意搜索范围是左闭右开区间

那么 lower_bound有什么用呢? 既然题中给的数字是无序的,我们不妨先排列一下,这样我们搜索的目标是 最大差的绝对值对吧,那么我们对 A 数组每个数加上这个最大差的绝对值, 看一看有几个数字比这个数字大 如果比他大数字之和 达到了总数量的一半,我们就成功的到达了答案 计算了一下复杂度 O(logn*n*logn) 应该能过 然后 AC了。

代码如下:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

const int maxn = 1e5+5;
int a[maxn];
int n, m;

bool test(int val)
{
    int cnt = 0;
    for(int i=0;i<n;i++)
    {
        cnt += n -(lower_bound(a,a+n,a[i]+val)-a);
    }
    return cnt > m;
}

int main()
{
    while(scanf("%d",&n)!=EOF)
    {
	     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(r - l > 1)//这里需要注意一下,如果是 r>l的话 最后会卡死 答案出错
         //举个例子 l=1,r=2 这块就会被卡死 需要注意一下
         {
             int mid = (l+r)>>1;
             if(test(mid)) l = mid;
             else r = mid;
         }
         printf("%d\n",l);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40924940/article/details/83743997
POJ