码迷,mamicode.com
首页 > 其他好文 > 详细

POJ3579 Median

时间:2017-10-09 17:43:32      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:enc   不难   数列   soft   class   etc   font   table   eve   

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\n", ans);
49     }
50     return 0;
51 } 
POJ2579

 

 

POJ3579 Median

标签:enc   不难   数列   soft   class   etc   font   table   eve   

原文地址:http://www.cnblogs.com/huibixiaoxing/p/7641844.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!