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
POJ Founder Monthly Contest – 2008.04.13, Lei Tao
正解:二分答案
解题报告:
今天考试的T2,考场上面还想了很久XD
因为是求处在中位数的差值,所以直接二分这个差值x,对于每个数查找整个数列有多少个比他大x以上的数有多少直接checke检查合法性。
1 //It is made by jump~ 2 #include <iostream> 3 #include <cstdlib> 4 #include <cstring> 5 #include <cstdio> 6 #include <cmath> 7 #include <algorithm> 8 #include <ctime> 9 #include <vector> 10 #include <queue> 11 #include <map> 12 #include <set> 13 using namespace std; 14 typedef long long LL; 15 #define RG register 16 const int MAXN = 50011; 17 int n; 18 LL a[MAXN]; 19 LL l,r,ans,ans2; 20 LL N,cnt,zhong; 21 22 inline int getint() 23 { 24 RG int w=0,q=0; char c=getchar(); 25 while((c<‘0‘ || c>‘9‘) && c!=‘-‘) c=getchar(); if(c==‘-‘) q=1,c=getchar(); 26 while (c>=‘0‘ && c<=‘9‘) w=w*10+c-‘0‘, c=getchar(); return q ? -w : w; 27 } 28 29 inline bool check(LL x){ 30 cnt=0; LL now; 31 for(RG int i=1;i<=n;i++) { 32 now=lower_bound(a+i,a+n+1,a[i]+x)-a; 33 cnt+=(LL)n-now+1; 34 } 35 if(cnt>zhong) return true; return false; 36 } 37 38 inline void work(){ 39 while(scanf("%d",&n)!=EOF) { 40 for(RG int i=1;i<=n;i++) a[i]=getint(); 41 sort(a+1,a+n+1); l=0; r=a[n]-a[1]+1; a[n+1]=(1<<30); 42 N=(LL)n*(n-1)/2; LL mid; 43 zhong=N/2; ans=0; 44 while(l<=r) { 45 mid=(l+r)/2; 46 if(check(mid)) ans=mid,l=mid+1; 47 else r=mid-1; 48 } 49 printf("%lld\n",ans); 50 } 51 } 52 53 int main() 54 { 55 work(); 56 return 0; 57 }