首页 > 其他 > 详细

POJ 3579

时间:2014-03-14 17:05:10      阅读:614      评论:0      收藏:0      [点我收藏+]
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

 
二分中位数
 
bubuko.com,布布扣
 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

 

POJ 3579,布布扣,bubuko.com

POJ 3579

原文:http://www.cnblogs.com/hyxsolitude/p/3600305.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!