POJ3579 Median【二分法+中位数】

Median

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 10335   Accepted: 3630

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 = 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

Source

POJ Founder Monthly Contest – 2008.04.13, Lei Tao

问题链接POJ3579 Median

问题描述

  n个数Xi(1<=i<=n),求其两两差的最中间的值。

问题分析

  使用二分法实现,并且使用STL的算法函数lower_bound()。

程序说明

  算法函数lower_bound()的功能是,查找有序区间中第一个大于或等于某给定值的元素的位置。

参考链接:(略)

题记:(略)

AC的C++语言程序如下:

/* POJ3579 Median */

#include <iostream>
#include <algorithm>
#include <stdio.h>

using namespace std;

const int N = 1e5;
int n, m, a[N];

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

int main()
{
    while(~scanf("%d", &n)) {
        for(int i = 0; i < n; i++)
            scanf("%d", &a[i]);

        sort(a, a + n);
        m = n * (n - 1) / 4;
        int lb = 0, ub = a[n-1], mid = (lb + ub) / 2;
        while (ub - lb > 1) {
            if (judge(mid))
                lb = mid;
            else
                ub = mid;
            mid = (lb + ub) / 2;
        }

        printf("%d\n", mid);
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/tigerisland45/article/details/81623765