【Luogu P7759】[COCI2014-2015#7] PROSJEK

[COCI2014-2015#7] PROSJEK:

题目大意:

给出包含一个 \(N\) 个整数的数组 \(A\)。找出一段长度至少为 \(K\) 的连续序列,最大化它的平均值。

思路:

二分答案,考虑到可以以当前平均值是否存在为 key。

代码:

const int N = 3e5 + 10;

inline ll Read()
{
	ll x = 0, f = 1;
	char c = getchar();
	while (c != '-' && (c < '0' || c > '9')) c = getchar();
	if (c == '-') f = -f, c = getchar();
	while (c >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0', c = getchar();
	return x * f;
}

int n, m;
double a[N], sum[N], l, r, mid;

bool check(double x)
{
	bool ans = 0;
	sum[0] = 0;
	for (int i = 1; i <= n; i++) 
		a[i] -= x, sum[i] = a[i] + sum[i - 1];
	double p = 0;
	for (int i = m; i <= n; i++)
	{
		if (sum[i] - p >= 0) {ans = 1; break;}
		p = min(p, sum[i - m + 1]);
	} 
	for (int i = 1; i <= n; i++) 
		a[i] += x;
	return ans;
}

int main()
{
	freopen("average.in", "r", stdin);
	freopen("average.out", "w", stdout);
	n = Read(), m = Read();
	for (int i = 1; i <= n; i++) 
		a[i] = Read(), r = max(r, a[i]);
	
	while (r - l > 1e-6)
	{
		mid = (l + r) / 2.0;
		if (check(mid)) l = mid;
		else r = mid;
	}
	
	printf ("%.5lf", l);
	return 0;
}
posted @ 2021-08-17 15:56  Jayun  阅读(45)  评论(0编辑  收藏  举报