1. A Best Cow Fences 二分
链接:https://ac.nowcoder.com/acm/contest/1000/A
来源:牛客网
题目描述
Farmer John’s farm consists of a long row of N (1≤N≤100,000) fields. Each field contains a certain number of cows,1≤ncows≤2000
FJ wants to build a fence around a contiguous group of these fields in order to maximize the average number of cows per field within that block. The block must contain at least F(1≤F≤N) fields, where F given as input.
Calculate the fence placement that maximizes the average, given the constraint.
题意翻译
给定一个长度为n的非负整数序列A,求一个平均数最大的,长度不小于L的子段 。
输入描述:
Line 1: Two space-separated integers, N and F.
Lines 2..N+1: Each line contains a single integer, the number of cows in a field.
Line 2 gives the number of cows in field 1,line 3 gives the number in field 2, and so on.
输出描述:
* Line 1: A single integer that is 1000 times the maximal average.
Do not perform rounding, just print the integer that is 1000×ncows\nfields.
示例1
输入
10 6
6
4
2
10
3
8
5
9
4
1
输出
6500
解题思路:
#include<bits/stdc++.h>
using namespace std ;
const int maxn=1e5;
int len,k;//序列长度和子序列最小长度
int cows[maxn];
double sum[maxn];
bool check(double average){
for(int i=1;i<=len;i++){//计算前缀和
sum[i]=sum[i-1]+cows[i]-average;
}
double minn=0;//在当前元素之前k个元素之前的元素的最小值
for(int i=k,j=0;i<=len;i++,j++){
minn=min(sum[j],minn);
if(sum[i]-minn>=0){//若平均数大于等于average就返回true
return true;
}
}
return false;
}
int main()
{
cin>>len>>k;
double l=0;
double r=0;
for(int i=1;i<=len;i++){
cin>>cows[i];
r=max((double)cows[i],r);
}
while(r-l>1e-5){//二分查找框架
double mid=(l+r)/2;
if(check(mid)) l=mid;
else r=mid;
}
printf("%d\n",(int)(1000*r));
}
斜率DP
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=1e5+10;
int sum[N],dp[N];
int q[N];
inline double calc(int j,int i) {//计算斜率
return (double)(sum[i]-sum[j])/(i-j);
}
int main()
{
int n,k;
while(scanf("%d%d",&n,&k)!=EOF)
{
sum[0]=0;
for(int i=1;i<=n;i++)
{
int val;
scanf("%d", &val);
sum[i]=sum[i-1]+val;//计算前缀和
}
double ans=0;
int l=1,r=0;
q[1]=0;
for(int i=k; i<=n; i++) {
int j=i-k;
while(l<r && calc(q[r], q[r-1] ) >=calc(i-k,q[r-1]))
r--;
q[++r]=j;
while(l<r && calc(q[l+1],i)>=calc(q[l],i))
l++;
ans=max(ans,1.0*(sum[i]-sum[q[l]])/(i-q[l]) );
}
printf("%d\n", (int)(ans*1000));
}
}