Average uvalive4726

题意:

输入一个串,求长度至少为k且平均值最大的字串的起始与结束位置

思路:

首先累加到每个为的总值,然后再枚举所有可能的终点,然后cur为最近的起点,q存储所有的起点,每次存储起点都要达到作为终点的最优

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 100005;
int n, l;
int sum[maxn];
int q[maxn];
char str[maxn];

double ave(int x, int y) {
	return (sum[y]-sum[x])*1.0/(y-x);
}
int main() {
	int kase;
	scanf("%d", &kase);
	while(kase--) {
		scanf("%d%d", &n, &l);
		sum[0] = 0;
		scanf("%s", str+1);
		for(int i=1; i<=n; i++) {
			sum[i] = sum[i-1]+(str[i]-'0');
		}
		int s=0, f=-1, len=l;
		double ans = ave(0, l);
		int ansl=0, ansr=l;
		for(int i=l; i<=n; i++) {
			int cur = i-l;
			while(f>s && ave(q[f], cur) <= ave(q[f-1], cur))
				f--;
			q[++f] = cur;
			while(f>s && ave(q[s], i) <= ave(q[s+1], i))
				s++;
			double b = ave(q[s], i);
			if(b > ans) {
				ansl = q[s];
				ansr = i;
				ans = b;
				len = i-q[s];
			}
			else if(b == ans && i-q[s] < len) {
				ansl = q[s];
				ansr = q[f];
				len = i-q[s];
			}
		}
		printf("%d %d\n", ansl+1, ansr);
	}
	return 0;
}

(不能达到最优的自然可以淘汰),然后在q内找到最优的起点最后调整

代码:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值