UVA - 1451 Average 单调队列 (数形结合-更新最大斜率)

找一段长度至少为L的区间 ,平均值最大
求前缀和,体现在坐标系中,就是 ( sum [ j ] - sum [ i - 1 ] ) ÷ ( j - i + 1 )
包含 i 的 i - j 之间的斜率
只要单调队列维护斜率最大值就好了

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <set>
#include <stack>
#include <queue>
#include <ctype.h>
#include <vector>
#include <algorithm>
#include <time.h>
// cout << "  ===  " << endl;

using namespace std;
typedef long long ll;
const int maxn = 100000 + 7, INF = 0x3f3f3f3f, mod = 1e9+7;
int T, n, L;
char s[maxn];
int sum[maxn], p[maxn];

int compare_average(int x1, int x2, int x3, int x4) {
    return (sum[x2]-sum[x1-1]) * (x4-x3+1) - (sum[x4]-sum[x3-1]) * (x2-x1+1);
}

int main() {
    scanf("%d", &T);
    while(T--) {
        scanf("%d %d %s", &n, &L, s+1);
        sum[0] = 0;
        for(int i = 1; i <= n; ++i)
            sum[i] = sum[i-1] + (s[i] - '0');
        int ansL = 1, ansR = L;

        int i = 0, j = 0;  // 单调找斜率最大
        for(int t = L; t <= n; ++t) {
            while(j-i > 1 && compare_average(p[j-2], t-L, p[j-1], t-L) >= 0) j--;

            p[j++] = t-L+1;  // 改变上凸点

            while(j-i > 1 && compare_average(p[i], t, p[i+1], t) <= 0) i++; // 右边是下凸点,就右移

            int c = compare_average(p[i], t, ansL, ansR);
            if(c > 0 || (c == 0 && t-p[i] < ansR - ansL) ) {
                ansL = p[i], ansR = t;
            }
        }
        printf("%d %d\n", ansL, ansR);
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值