POJ 3579 - Median 题解
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ 3579 - Median 题解相关的知识,希望对你有一定的参考价值。
此文为博主原创题解,转载时请通知博主,并把原文链接放在正文醒目位置。
题目链接:http://poj.org/problem?id=3579
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<cstring> 3 #include<cstdio> 4 #include<algorithm> 5 #include<cmath> 6 7 const int MAXN = 100005; 8 9 inline void read(long long &x) 10 { 11 char ch = getchar(),c = ch;x = 0; 12 while(ch < ‘0‘ || ch > ‘9‘) c = ch,ch = getchar(); 13 while(ch <= ‘9‘ && ch >= ‘0‘) x = (x<<1)+(x<<3)+ch-‘0‘,ch = getchar(); 14 if(c == ‘-‘) x = -x; 15 } 16 17 long long n,l,r,mid,base,ans; 18 long long num[MAXN]; 19 20 bool jud(int x) 21 { 22 long long cnt = 0,L = 1,R = 2; 23 for(;L < n;++ L) 24 { 25 while(num[R] - num[L] <= x && R <= n) ++ R; 26 cnt += R-L-1; 27 } 28 if(cnt >= base) return true; 29 return false; 30 } 31 32 int main() 33 { 34 // freopen("1.txt","r",stdin); 35 while(scanf("%d",&n) != EOF) 36 { 37 base = (long long)(n*(n-1)/2+1)/2; 38 for(int i = 1;i <= n;++ i) 39 read(num[i]); 40 std::sort(num+1,num+1+n); 41 l = 1,r = num[n]; 42 while(l <= r) 43 { 44 mid = (l+r)>>1; 45 if(jud(mid)) ans = mid,r = mid-1; 46 else l = mid+1; 47 } 48 printf("%lld\n",ans); 49 } 50 return 0; 51 }
以上是关于POJ 3579 - Median 题解的主要内容,如果未能解决你的问题,请参考以下文章