Divide and conquer:Median(POJ 3579)

时间:2023-03-08 23:01:16
Divide and conquer:Median(POJ 3579)

                Divide and conquer:Median(POJ 3579)

                快速求两数距离的中值

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

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

  

 #include <iostream>
#include <algorithm>
#include <functional> using namespace std;
typedef long long LL_INT; static int nums[];
bool judge(LL_INT, LL_INT,const int); int main(void)
{
int lb, rb, mid;
LL_INT k, n; while (~scanf("%lld", &n))
{
k = n*(n - ) / ;
k = k % == ? k / : k / + ; for (int i = ; i < n; i++)
scanf("%d", &nums[i]);
sort(nums, nums + n);
lb = ; rb = ;
while (rb - lb > )
{
mid = (lb + rb) / ;
if (judge(k, n, mid)) lb = mid;
else rb = mid;
}
printf("%d\n", rb);
}
return ;
} bool judge(LL_INT k, LL_INT n,const int x)
{
int i = , sum = , pos = ;
for (; i < n; i++)
{
for (; pos < n && nums[pos] - nums[i] <= x; pos++);
sum += pos - i - ;
if (sum >= k)
return false;
}
return true;
}

  Divide and conquer:Median(POJ 3579)