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;
} 
全部评论

相关推荐

10-30 19:23
已编辑
山东大学(威海) C++
牛至超人:我了个雷 1.实习经历写太长了吧,精简一点,你写那么老多,面试官看着都烦 2.项目经历你放俩竞赛干啥单独拿出来写上几等奖就行了呗 3.一大雷点就是项目经历里的那个课程设计,大家都知道课程设计巨水,不要写课程设计,换一个名字,就叫学生管理系统,面试官问就说是自己做的项目,不要提课程设计的事 4.那个交流经历,简化一下塞到最上面的教育经历里就行了 5.简历尽量一页纸
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务