Median
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 8371 | Accepted: 2911 |
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
【题解】
二分中位数,将原数列排序,不难发现中位数配对数具有单调性,
即对于降序序列S,其中一个数Sp若Sl~Sr内的数与Sp差均小于ans,
则Sp+1与Sl~Sr内的数与Sp的差也一定小于ans,尺取法即可
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <cstring> 5 #include <algorithm> 6 #define max(a, b) ((a) > (b) ? (a) : (b)) 7 #define min(a, b) ((a) < (b) ? (a) : (b)) 8 9 inline void read(long long &x) 10 { 11 x = 0;char ch = getchar(), c = ch; 12 while(ch < '0' || ch > '9')c = ch, ch = getchar(); 13 while(ch <= '9' && ch >= '0')x = x * 10 + ch - '0', ch = getchar(); 14 if(c == '-')x = -x; 15 } 16 17 const long long MAXN = 100000 + 10; 18 19 long long n,num[MAXN]; 20 21 long long check(long long ans) 22 { 23 long long tot = 0; 24 long long r = 2; 25 for(register long long l = 1;l <= n;++ l) 26 { 27 while(num[r] - num[l] <= ans && r <= n)++ r; 28 tot += r - l - 1; 29 } 30 if(tot >= (n * (n - 1)/2 + 1)/2 )return 1; 31 else return 0; 32 } 33 34 int main() 35 { 36 while(scanf("%lld", &n) != EOF) 37 { 38 long long ma = -1; 39 for(register long long i = 1;i <= n;++ i) read(num[i]), ma = max(ma, num[i]); 40 std::sort(num + 1, num + 1 + n); 41 long long l = 1, r = ma, ans = 0; 42 while(l <= r) 43 { 44 long long mid = (l + r) >> 1; 45 if(check(mid))ans = mid, r = mid - 1; 46 else l = mid + 1; 47 } 48 printf("%lld ", ans); 49 } 50 return 0; 51 }