POJ3579 Median —— 二分

Posted h_z_cong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ3579 Median —— 二分相关的知识,希望对你有一定的参考价值。

题目链接:http://poj.org/problem?id=3579

 

Median
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 8286   Accepted: 2892

Description

Given N numbers, X1X2, ... , 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 = 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 X1X2, ... , XN, ( X≤ 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 <cstring>
 4 #include <cmath>
 5 #include <algorithm>
 6 #include <vector>
 7 #include <queue>
 8 #include <stack>
 9 #include <map>
10 #include <string>
11 #include <set>
12 #define ms(a,b) memset((a),(b),sizeof((a)))
13 using namespace std;
14 typedef long long LL;
15 const double EPS = 1e-8;
16 const int INF = 2e9;
17 const LL LNF = 2e18;
18 const int MAXN = 1e5+10;
19 
20 int n, a[MAXN];
21 int m;
22 
23 bool test(int mid)
24 {
25     int cnt = 0;
26     for(int i = 1; i<=n; i++)
27         cnt += upper_bound(a+i+1, a+1+n, a[i]+mid)-(a+i+1);
28     return cnt>=m;
29 }
30 
31 int main()
32 {
33     while(scanf("%d", &n)!=EOF)
34     {
35         for(int i = 1; i<=n; i++)
36             scanf("%d", &a[i]);
37 
38         sort(a+1, a+1+n);
39         m = n*(n-1)/2;
40         m = (m+1)/2;
41         int l = 0, r = a[n]-a[1];
42         while(l<=r)
43         {
44             int mid = (l+r)>>1;
45             if(test(mid))
46                 r = mid - 1;
47             else
48                 l = mid + 1;
49         }
50         printf("%d\n", l);
51     }
52 }
View Code

 

 

以上是关于POJ3579 Median —— 二分的主要内容,如果未能解决你的问题,请参考以下文章

POJ-3579 Median---二分第k大(二分套二分)

POJ 3579 Median(二分答案+Two pointers)

POJ - 3579 Median(二分)

POJ 3579 Median

POJ3579 Median

POJ 3579 - Median 题解