POJ 3579 Median (二分)
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 7423 | Accepted: 2538 |
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
1 #include<iostream> 2 #include<cstdio> 3 #include<cstdlib> 4 #include<cctype> 5 #include<cmath> 6 #include<cstring> 7 #include<map> 8 #include<stack> 9 #include<set> 10 #include<vector> 11 #include<algorithm> 12 #include<string.h> 13 typedef long long ll; 14 typedef unsigned long long LL; 15 using namespace std; 16 const int INF=0x3f3f3f3f; 17 const double eps=0.0000000001; 18 const int N=100000+10; 19 int a[N];int n,m; 20 int judge(int x){ 21 int sum=0; 22 for(int i=0;i<n;i++){ 23 int t=lower_bound(a,a+n,a[i]+x)-a; 24 // 存在差值 x 25 sum=sum+n-t;// 和a[i]的差值小于等于x的个数为n-t; 26 } 27 if(sum>m)return 1; 28 else{ 29 return 0; 30 } 31 } 32 int main(){ 33 34 while(scanf("%d",&n)!=EOF){ 35 int maxx=0; 36 for(int i=0;i<n;i++){ 37 scanf("%d",&a[i]); 38 } 39 sort(a,a+n); 40 m=n*(n-1)/4; 41 int low=0; 42 int ans; 43 int high=a[n-1]; 44 while(low<=high){ 45 int mid=(low+high)>>1; 46 if(judge(mid)){ 47 ans=mid; 48 low=mid+1; 49 } 50 else 51 high=mid-1; 52 } 53 cout<<ans<<endl; 54 } 55 }