您的位置:首页 > 其它

POJ - 3579 Median (二分 + 查找第K大)

2016-08-09 10:54 330 查看
Median

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 5866 Accepted: 1947
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

不多说,上代码

#include <cstdio>
#include <cstring>
#include <algorithm>

#define FOUT freopen("output.txt", "w+", stdout)

using namespace std;

typedef long long LL;
const int MAXN = 1e5 + 5;
int n, A[MAXN];
LL k;
bool C(int m){
LL res = 0;
for(int i = 0;i < n;i ++){
res += A + n - lower_bound(A + i, A + n, A[i] + m + 1);
}
return res > k;
}
int main(){
//FOUT;
while(~scanf("%d", &n)){
int Max = 0;
for(int i = 0;i < n;i ++){
scanf("%d", &A[i]);
Max = max(Max, A[i]);
}
k = (LL)n * (n - 1) / 4;
sort(A, A + n);
int lb = -1, ub = Max;
while(ub - lb > 1){
int mid = (ub + lb) >> 1;
if(C(mid)){
lb = mid;
}
else{
ub = mid;
}
}
printf("%d\n", ub);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: