题解:CF2126B No Casino in the Mountains

· · 题解

思路

首先,利用 last 表示最后一个 1 出现的地方,由此算出每个连续的0串,我把它存到了 num[] 中。

然后推出关键句:

ans += \lfloor s / k \rfloor

其中设连续的0串长度为 s, 答案数量为 ans 。不难发现需要分类讨论。

  1. 当 s < k 时,ans 不需要更改。
  2. 当 s = k 时,ans 要加 1。
  3. 当 s = k 时, 需要额外分析一下。

由题意得:每两个连续 k 个 0串间需要有一个格外的0, 我们可以把 k 个0串与额外的一个0组合起来。 所以

ans += \lfloor s / k \rfloor

应改为:

ans += \lfloor s / (k + 1) \rfloor

但每次计算的末尾的一组少了一个0,所以需要补上,所以最终的关键语句(主要思想)为

ans += \lfloor (s + 1) / (k + 1) \rfloor

时间复杂度:O(n)

其他细节注释在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;
}