题目
思路
代码
#include <cstdio>
#include <cstdlib>
const int maxn = 100000 + 1000;
int num[maxn], sum[maxn], n, L, p[maxn];
char s[maxn];
// 有效避免除法
int cmp(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() {
int T;
scanf("%d", &T);
while (T--) {
scanf("%d%d%s", &n, &L, s + 1);
for (int i = 1; i <= n; i++) num[i] = s[i] - '0';
sum[0] = 0;
for (int i = 1; i <= n; i++) sum[i] = sum[i - 1] + num[i];
int ansL = 1, ansR = L, i = 0, j = 0;
for (int t = L; t <= n; t++) {
while (i < j - 1 && cmp(p[j - 2], p[j - 1], p[j - 1], t - L) > 0) j--;
p[j++] = t - L + 1;
while (i < j - 1 && cmp(p[i + 1], t, p[i], t) >= 0) i++;
int c = cmp(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;
}
感悟
1.此题虐我千百遍,我仍待此题如初恋。。
2.折磨了我将近半个月,思路那是相当清晰,但就是调不出来,跟udebug上数据一对比,总有各种各样的错误,干脆拿来LRJ的算了。自我感觉这道题理解地够清晰了。
3.也算烂尾吧。。比较有关形的题基本没做过,一上来就做这种难度的,调不出来也是没办法。