Best Cow Fences(POJ-2018)
Problem Description
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.
Input
* 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.
Output
* 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.
Sample Input
10 6
6
4
2
10
3
8
5
9
4
1Sample Output
6500
题意:给出 n 个数,和一个长度 F,现在要找一个平均数最大的长度不小于 F 的子段,并将这个最大值乘以 1000 然后输出
思路:
问题实质是让找出一个长度不小于 F 的子段,使得平均数不小于二分结果的值
将数列中的每一个数都减去二分结果的值,那么问题判定就转换成:找一个长度不下小于 F 的子段,使得字段和非负
对于字段和非负问题,如果没有长度 F 的限制,那么可以借助队列,不断将新数据加入队列,一旦队列和变为负数,即将队列清空,扫描过程中出现的最大队列和即为所求
然而此问题要求子段长度不小于 F,那么可以将子序列和转成前缀和相减的形式,即用 sum[i] 来表示 a[1]~a[i] 的和,每次与新的取值 sum[i]-sum[F] 取最小即可
Source Program
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<bitset>
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
#define Pair pair<int,int>
const double EPS = 1E6;
const int MOD = 1E9+7;
const int N = 1000000+5;
const int dx[] = {-1,1,0,0,-1,-1,1,1};
const int dy[] = {0,0,-1,1,-1,1,-1,1};
using namespace std;
int n,f;
double a[N];
double sub[N];
double sum[N];
int main() {
scanf("%d%d",&n,&f);
for(int i=1;i<=n;i++)
scanf("%lf",&a[i]);
double left=-1E6,right=1E6;
while(right-left>1E-5){
double mid=(left+right)/2.0;
for(int i=1;i<=n;i++){
sub[i]=a[i]-mid;//作差
sum[i]=sum[i-1]+sub[i];//前缀和
}
double ans=-1E10;
double minn=1E10;
for(int i=f;i<=n;i++){
minn=min(minn,sum[i-f]);
ans=max(ans,sum[i]-minn);
}
if(ans>=0)
left=mid;
else
right=mid;
}
int res=right*1000;
printf("%d\n",res);
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探