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

 
分析:
这题的思路比较巧妙...是学大伟业讲基础算法的例题。
直接求中位数就只能暴力了,这里采用二分答案。
二分一个数字x,然后判断它是不是差的中位数。
判断方法是计算有多少个num[i]-num[j] <= x,如果这个数目超过差值总数的1/2,显然我们枚举的x过大。
当然双重循环计算num[i]-num[j]是非常不明智的。我们可以对num[]从小到大排序,再进行计算。
举个栗子,如果排序后num[r] - num[l] <= x,那么num[r] - num[k]必定也<= x (l < k < r).
因此不需要每次循环r,只需保留对上一个l循环到的r值,继续向后推进到差值 > x即可。
 
AC代码:
 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 题解的主要内容,如果未能解决你的问题,请参考以下文章

POJ3579 Median —— 二分

POJ3579 Median

POJ3579 Median

POJ 3579 Median 二分+思维

POJ 3579 Median

POJ - 3579 Median(二分)