UVA

来源:互联网 发布:python设计模式豆瓣 编辑:程序博客网 时间:2024/05/23 20:14

找一段长度至少为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;}