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

Divide and conquer:Median(POJ 3579)

时间:2016-01-18 22:51:49      阅读:327      评论:0      收藏:0      [点我收藏+]

标签:

                技术分享

                快速求两数距离的中值

  题目大意:给你一个很大的数组,要你求两个数之间的距离的中值

  二分法常规题,一个pos位就搞定的事情

  

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <functional>
 4 
 5 using namespace std;
 6 typedef long long LL_INT;
 7 
 8 static int nums[100002];
 9 bool judge(LL_INT, LL_INT,const int);
10 
11 int main(void)
12 {
13     int lb, rb, mid;
14     LL_INT k, n;
15 
16     while (~scanf("%lld", &n))
17     {
18         k = n*(n - 1) / 2;
19         k = k % 2 == 0 ? k / 2 : k / 2 + 1;
20 
21         for (int i = 0; i < n; i++)
22             scanf("%d", &nums[i]);
23         sort(nums, nums + n);
24         lb = 0; rb = 1000000001;
25         while (rb - lb > 1)
26         {
27             mid = (lb + rb) / 2;
28             if (judge(k, n, mid)) lb = mid;
29             else rb = mid;
30         }
31         printf("%d\n", rb);
32     }
33     return 0;
34 }
35 
36 bool judge(LL_INT k, LL_INT n,const int x)
37 {
38     int i = 0, sum = 0, pos = 1;
39     for (; i < n; i++)
40     {
41         for (; pos < n && nums[pos] - nums[i] <= x; pos++);
42         sum += pos - i - 1;
43         if (sum >= k) 
44             return false;
45     }
46     return true;
47 }

  技术分享

Divide and conquer:Median(POJ 3579)

标签:

原文地址:http://www.cnblogs.com/Philip-Tell-Truth/p/5140584.html

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