【数据结构练习】平均数【二分答案】【树状数组】

题目描述

【数据结构练习】平均数【二分答案】【树状数组】_第1张图片

思路:

我们直接二分一个平均数,然后让a全部减去它,问题就变成了前缀和中的逆序对问题

c o d e code code

#include
#include
#include
#include
#define ll long long

#define lowbit(x) x & -x 

using namespace std;

const ll MAXN = 1e5 + 10;

ll n, k;
double a[MAXN], b[MAXN], c[MAXN];
ll tr[MAXN];

void add(ll x, ll y) {
	for(; x <= n; x += lowbit(x)) tr[x] += y;
}

ll query(ll x) {
	ll ans = 0;
	for(; x; x -= lowbit(x)) ans += tr[x];
	return ans;
}

ll check(double tmp) {
	memset(tr, 0, sizeof(tr));
	for(ll i = 1; i <= n; i ++) a[i] -= tmp, b[i] = b[i - 1] + a[i], c[i] = b[i];
	sort(c + 1, c + 1 + n);
	ll tot = unique(c + 1, c + 1 + n) - c - 1, ans = 0, ans2 = 0;
	for(ll i = 0; i <= n; i ++) {
		b[i] = lower_bound(c + 1, c + 1 + tot, b[i]) - c;
		ans += query(b[i]);
		ans2 += query(b[i]); 
		add(b[i], 1);
		a[i] += tmp;
	}
	return ans < k;
}

int main() {
	scanf("%lld%lld", &n, &k);
	for(ll i = 1; i <= n; i ++) scanf("%lf", &a[i]);
	double l = 0, r = 1000000.0;
	while(l + 0.0000001 < r) {
		double mid = (l + r) / 2.0;
		if(check(mid)) r = mid;
		else l = mid;
	}
	printf("%.6lf", (l + r) / 2);
	return 0;
}

你可能感兴趣的:(题解,#,树状数组,二分,数据结构,算法,c++,题解,二分答案)