POJ_3579_Median_(二分,查找第k大的值)
描述
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.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<cstdio> 2 #include<algorithm> 3 using std :: sort; 4 using std :: lower_bound; 5 6 const int maxn=100005; 7 int n,N; 8 int a[maxn]; 9 10 bool C(int d) 11 { 12 int cnt=0; 13 for(int i=1;i<n;i++) cnt+=a+n-(lower_bound(a+i+1,a+n+1,a[i]+d)-1); 14 return cnt<=N/2; 15 } 16 17 void solve() 18 { 19 sort(a+1,a+n+1); 20 int l=0,r=a[n]-a[1]; 21 while(l<r) 22 { 23 int m=l+(r-l+1)/2; 24 if(C(m)) r=m-1; 25 else l=m; 26 } 27 printf("%d\n",l); 28 } 29 30 void init() 31 { 32 while(scanf("%llu",&n)==1) 33 { 34 N=n*(n-1)/2; 35 for(int i=1;i<=n;i++) scanf("%d",&a[i]); 36 solve(); 37 } 38 } 39 40 int main() 41 { 42 init(); 43 return 0; 44 }