POJ - 3579 Median
POJ - 3579 Median
二分套二分
Median - POJ 3579 - Virtual Judge (vjudge.net)
对数轴上的点排序后,可枚举左端点,固定左端点后,区间长度关于右端点是单调递增的,因此可以二分
- 二分答案
- check 返回有多少区间小于当前的二分值,求有多少区间的过程可以枚举左端点,二分右端点
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
typedef long long ll;
const int N = 1e5 + 10;
int a[N];
int n;
ll m;
ll check(int x)
{
ll cnt = 0;
for (int i = 1; i < n; i++)
{
int l = i, r = n + 1;
while(l + 1 != r)
{
int mid = l + r >> 1;
if (a[mid] - a[i] < x)
l = mid;
else
r = mid;
}
cnt += l - i;
}
return cnt;
}
int main()
{
while(scanf("%d", &n) != EOF)
{
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
sort(a + 1, a + n + 1);
m = 1ll * n * (n - 1) / 2;
m = (m + 1) / 2;
int l = 0, r = 1e9 + 1;
while(l + 1 != r)
{
int mid = l + r >> 1;
if (check(mid) < m)//比mid小的有几个
l = mid;
else
r = mid;
}
printf("%d\n", l);
}
return 0;
}