POJ 3579 Median

Median

Time Limit: 1000MS Memory Limit: 65536K

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

思路:

刚看题目,肯定暴力是最简单的方法,但是数据实在太大了,所以就要用其他方法了,所以就用双重二分了,首先要求出有多少个数,再求中位数的位置就有n * (n - 1) / 4就是中位数的位置了,然后就是如何求出位置了,先找中位数为多少,然后就是找大于等于这个中位数加上i位置的数字的位置,既然能够大于等于那么在这个数字后面的也一定能够大于等于,所以就是用n-位置,0-n-1的数量总和就是大于等于中位数的数量总和,然后用二分的方法确定最后的中位数。

#include <iostream>
#include <algorithm>
using namespace std;
int n, m;
int a[100010];
int check(int x) {
	int sum = 0;
	for (int i = 0; i < n; i++) {
		sum += n - (lower_bound(a, a + n, a[i] + x) - a);
	}
	return sum;
}
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) {
			int mid = (l + r) >> 1;
			if (check(mid) <= m) r = mid;
			else l = mid;
			
		}
		cout << (l + r) / 2 << endl; 
	}
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值