码迷,mamicode.com
首页 > 其他好文 > 详细

POJ3579 Median —— 二分

时间:2017-09-21 22:27:14      阅读:309      评论:0      收藏:0      [点我收藏+]

标签:ring   not   search   题目   size   width   UI   accept   arch   

题目链接: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 —— 二分

标签:ring   not   search   题目   size   width   UI   accept   arch   

原文地址:http://www.cnblogs.com/DOLFAMINGO/p/7571445.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!