POJ 3579 Median 二分答案

题意:给出一串序列,可以用这些序列值算出C(N,2)个|a[i]-a[j]|值,求出这些值中的中位数
思路:对每个数二分,对于每个i在序列中查找存在的大于a[i]+m的数的个数之和,即找出|a[i]-a[j]|<m的数的个数,答案即为个数恰好为C(N,2)/2时的m

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<vector>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn = 1e5+5;
const int inf = 0x3f3f3f3f;
int n, a[maxn], k;
bool solve(int m)
{
	int sum = 0;
	for (int i = 0; i < n; i++)
		sum += n - (lower_bound(a+i+1, a+n, a[i]+m)-a);
	return sum > k;
}
int main()
{
	while (~scanf("%d", &n)) {
		for (int i = 0; i < n; i++)
			scanf("%d", &a[i]);
		k = n * (n-1) / 4;
		sort(a, a+n);
		int l = 0, r = 1e9;
		while (l <= r) {
			int mid = (l+r) >> 1;
			if (solve(mid)) {
				l = mid + 1;
			} else 
				r = mid - 1;
		}
		printf("%d\n", r);
	}
}
上一篇:2019牛客多校第七场E Find the median 离散化+线段树维护区间段


下一篇:详解python statistics模块及函数用法