POJ3579_Median_二分求第k大(两重二分)

快速求解中位数差异
本文介绍了一种高效算法,用于求解给定数列中所有两两元素之差的中位数。通过两次使用二分查找技巧,显著提高了计算效率。

Median
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 7293 Accepted: 2484

Description

Given N numbers, X1X2, ... , 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 X1X2, ... , XN, ( X≤ 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


给出一个含有 n 个元素的数列, 求各元素差的中位数。


运用两次二分。

第一次二分枚举中位数 md, 判断依据是小于等于 md 的差的个数。

求小于等于 md 的差的个数时,用到了第二次二分。

给公式:a[j] - a[i] <= md  =>  a[j] <= a[i] + md 。

所以只需要在排好序的 a 数组里用 upper_bound就可以轻易求出 a[i] 为被减数的小于等于 md 的差的个数。然后让 i 遍历 0 - n-1 好了。


#include<cstdio>
#include<iostream>
#include<algorithm>

using namespace std;

const int maxn = 100100;
const int inf  = 0x3f3f3f3f;

int a[maxn];

bool C(int md, int k, int n)
{
	int cnt = 0;

	//求有多少个 a 中元素两两相减的差 <= md

	//枚举 a[i]
	//求有多少个j满足 a[j] - a[i] <= md
	//a[j] <= a[i] + md
	//所以只要二分计数 a 中小于等于 a[i] + md 的个数就可以了
	for(int i= 0; i< n; i++){
		cnt += upper_bound(a+i+1, a+n, a[i]+md) - a - i - 1;
		if(cnt >= k) return true;
	}

	return false;
}

int main ()
{
	int n;
	while(~scanf("%d", &n)){

		//中值是第几大
		int k = (n * (n-1) / 2 + 1) / 2;

		for(int i= 0; i< n; i++)
			scanf("%d", a+i);
		sort(a, a+n);

		//二分枚举 答案
		int lb = 0, ub = inf;
		while(lb <= ub){

			int md = (lb + ub) >> 1;

			if(C(md, k, n)) ub = md - 1;
			else lb = md + 1;
		}

		printf("%d\n", ub+1);
	}

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值