描述
http://poj.org/problem?id=3579
给你一串数,共C(n,2)个差值(绝对值),求差值从大到小排序的中值,偶数向下取.
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 5468 | Accepted: 1762 |
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
Source
分析
可以先把数排序,然后下界0,上界a[n]-a[1],二分假定中值d,如果所有差值中大于等于d的小于等于N/2,说明d太大了.判断d是否可行时如果枚举差值就太慢了,可以对于每一个数x,找所有满足xi>=x+d(xi>x)的xi的个数,这里还是用二分,直接lower_bound即可.
注意:
1.差值共有N=C(n,2)=n*(n-1)/2而不是n.
2.数据范围并不会超int.
#include<cstdio>
#include<algorithm>
using std :: sort;
using std :: lower_bound; const int maxn=;
int n,N;
int a[maxn]; bool C(int d)
{
int cnt=;
for(int i=;i<n;i++) cnt+=a+n-(lower_bound(a+i+,a+n+,a[i]+d)-);
return cnt<=N/;
} void solve()
{
sort(a+,a+n+);
int l=,r=a[n]-a[];
while(l<r)
{
int m=l+(r-l+)/;
if(C(m)) r=m-;
else l=m;
}
printf("%d\n",l);
} void init()
{
while(scanf("%llu",&n)==)
{
N=n*(n-)/;
for(int i=;i<=n;i++) scanf("%d",&a[i]);
solve();
}
} int main()
{
init();
return ;
}