思路
首先,利用 表示最后一个 出现的地方,由此算出每个连续的0串,我把它存到了 中。
然后推出关键句:
其中设连续的0串长度为 , 答案数量为 。不难发现需要分类讨论。
- 当 时, 不需要更改。
- 当 时, 要加 。
- 当 时, 需要额外分析一下。
由题意得:每两个连续 个 0串间需要有一个格外的0, 我们可以把 个0串与额外的一个0组合起来。 所以
应改为:
但每次计算的末尾的一组少了一个0,所以需要补上,所以最终的关键语句(主要思想)为
时间复杂度:
其他细节注释在AC代码中。
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int t;
int n, k;
int a[N];
int num[N], cnt = 0, f = 0, ans = 0;
int main() {
cin >> t;
while (t--) {
int last = 0, ans = 0;
cnt = 0;
cin >> n >> k;
a[n + 1] = 1; //防止出现整个01串只有0导致num数组存储错误的情况
for (int i = 1; i <= n; i++) cin >> a[i];
for (int i = 1; i <= n + 1; i++) {
if (a[i] == 1) {
num[cnt++] = i - 1 - last;
last = i;
}
}
for (int i = 0; i < cnt; i++) {
int x = num[i];
if (x < k) continue;
else if (x == k) ans++;
else {
ans += (x + 1) / (k + 1); // 注意这行代码
}
}
cout << ans << endl;
}
return 0;
}