Official

B - Strawberries Editorial by en_translator


He can eat the maximum number of strawberries by following this procedure: if the \(i\)-th through \((i+K-1)\)-th teeth are all healthy, use them to eat a strawberry, and set the \(i\)-th through \((i+K-1)\)-th characters of \(S\) to X, for each \(i=1,2,\ldots,N-K+1\) in this order.

This can be proven optimal because, given consecutive healthy teeth, it is optimal to repeatedly use \(K\) leftmost teeth.

When implementing, operations against a string is required. Some language features for string handling may facilitate and shorten implementation. For example, one can use substr function in C++ to extract a substring, to simplify the implementation.

Sample code (C++)

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n, k;
    cin >> n >> k;
    string s;
    cin >> s;
    int ans = 0;
    string t = string(k, 'O');
    for (int i = 0; i < n - k + 1; ++i) {
        if (s.substr(i, k) == t) {
            ans++;
            for (int j = i; j < i + k; j++) {
                s[j] = 'X';
            }
        }
    }
    cout << ans << endl;
}

Sample code (Python3)

n, k = map(int, input().split())
s = list(input())
ans = 0
t = 'O' * k

for i in range(n - k + 1):
    if s[i:i + k] == list(t):
        ans += 1
        for j in range(i, i + k):
            s[j] = 'X'

print(ans)

posted:
last update: