[YBT high-efficiency advanced] 1 basic algorithm/3 bisection algorithm/3 maximum mean value

[YBT high-efficiency advanced] 1 basic algorithm/3 bisection algorithm/3 maximum mean value

Memory limit: 256 MiB
Time limit: 1000 ms
standard input and output
Question type: Traditional
Evaluation method: Text comparison

Title description

Given a sequence of positive integers AAA , find the one with the largest average, the length is not less thanLLThe (continuous) sub-segment of L.

Input format

Two integers NN in the first lineN andLLL

Next NNN lines, each line enter a positive integerA i A_iAi

Output format

Output an integer, which means that the maximum value of the average value is multiplied by 1000 10001 0 0 0 The result obtained after rounding down.

Sample

Sample input

10 6
6 
4
2
10
3
8
5
9
4
1

Sample output

6500

Data range and tips

对于 100% 的数据 1 < = n < = 1 0 5 , 1 < = L < = N , 1 < = A i < = 2000 1<=n<=10^5,1<=L<=N,1<=A_i<=2000 1<=n<=1051<=L<=N1<=Ai<=2000

Ideas

Dichotomous answer
Real number
dichotomy
Find the prefix sum of each number -mid Calculate
the largest sub-segment of length >=L
if sum>=0 l=mid
howho<0 r=mid

Code

#include<iostream>
#include<cstdio>
using namespace std;
double a[200010],sum[200010];
int n,L;
bool check(double x)
{
    
    
	double ans=-10000000000,mn=10000000000;
	int i;
	for(i=1;i<=n;i++)//前缀和 
		sum[i]=sum[i-1]+a[i]-x;
	for(i=L;i<=n;i++)
	{
    
    
		mn=min(mn,sum[i-L]);//当前最小值 
		ans=max(ans,sum[i]-mn);//最大子段和 
	}
	return ans>=0;
}
int main()
{
    
    
	double l,r,mid;
	int i;
	ios::sync_with_stdio(false);
	for(cin>>n>>L,i=1;i<=n;i++)
		cin>>a[i];
	for(l=-1000000,r=1000000;l+0.00001<r;)//二分答案 
	{
    
    
		mid=(l+r)/2;
		if(check(mid))l=mid;
		else r=mid;
	}
	cout<<int(r*1000)<<endl;
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_46975572/article/details/115143269