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.对数组进行排序。计算出有多少对数,并计算出中位数所在的位置m。
2.二分中位数mid,然后检测有多少对数的差小于等于mid。假设有cnt对,如果cnt>=m,那么缩小中位数;否则扩大中位数。
3.注意:upper_bound()、lower_bound()的区间是 前闭后开
 
 
代码如下:
 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); //在[i+1, n+1)的范围,即[i+1,n]
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

 

 

转载于:https://www.cnblogs.com/DOLFAMINGO/p/7571445.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值