POJ 3579

Median
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 3528 Accepted: 1001

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

 
二分中位数
 
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 
 6 using namespace std;
 7 
 8 #define maxn 100005
 9 #define INF 200005
10 typedef long long ll;
11 
12 int n;
13 int a[maxn],dis[maxn];
14 ll num;
15 
16 bool judge(int x) {
17 
18     int pos,i = 1,now = 0;
19     ll sum = 0;
20     while(i < n) {
21             pos = upper_bound(dis + 1,dis + n + 1,x + now) - dis;
22             sum += n - (pos);
23             now = dis[i];
24             if((n - 1) - pos + 1 == 0) break;
25             ++i;
26     }
27 
28     //printf("x = %d sum = %lld\n",x,sum);
29 
30     return num - sum - (num % 2) >= sum;
31 }
32 
33 void solve() {
34 
35     num = (ll)n * (n - 1) / 2;
36 
37     int l = INF,r = a[n] - a[1];
38     for(int i = 1; i < n; ++i) {
39             dis[i] = a[i + 1] - a[1];
40             l = min(l,a[i + 1] - a[i]);
41            // printf("%d ",dis[i]);
42     }
43     dis[n] = INF;
44 
45     //printf("l = %d r = %d\n",l,r);
46 
47     while(l < r) {
48             int mid = (l + r) >> 1;
49             if(judge(mid)) {
50                     r = mid;
51             } else {
52                     l = mid + 1;
53             }
54     }
55 
56     printf("%d\n",l);
57 
58 }
59 
60 int main()
61 {
62    // freopen("sw.in","r",stdin);
63 
64     while(~scanf("%d",&n)) {
65             for(int i =  1; i <= n; ++i) {
66                     scanf("%d",&a[i]);
67             }
68 
69             sort(a + 1,a + n + 1);
70 
71             solve();
72     }
73 
74 
75     return 0;
76 }
View Code

 

转载于:https://www.cnblogs.com/hyxsolitude/p/3600305.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值