Official

G - offence Editorial by en_translator


Let \(dp_{l,r}\) be the answer when the input string is the substring of \(S\) consisting of its \(l\)-th through \((r-1)\)-th characters. (“DP” stands for Dynamic Programming.)

What we want is \(dp_{0,|S|}\); we compute the answer in manner of segment DP. We evaluate \(dp_{l,r}\) considering the last position the operation was applied on.

1. If the operation was not applied

The length is \(r-l\).

2. If the o chosen in the last operation was the \(l\)-th character

We brute-force the positions of f. If we want to obtain of using the f at the \(i\)-th character, then it is necessary that all the characters from the \((l+1)\)-th through \((i-1)\) must be removed; in other words, \(dp_{l+1,i} = 0\). In this case, at most \(K\) characters starting from the \((i + 1)\)-th one can be removed, so the minimum length of the remaining string is \(\max(dp_{i+1,r} - K, 0)\).

3. If the o chosen in the last operation was not the \(l\)-th character

Suppose that the o at the \(i\)-th position was chosen. Then, since \(i\)-th character is not removed, we can consider before and after the \(i\)-th character independently. Therefore, the minimum length of the remaining string is \(dp_{l,i} + dp_{i,r}\).

Therefore, when we know the values \(dp_{l',r'}\) for all \((l', r')\) such that \(r-l > r'-l'\), we can evaluate \(dp_{l,r}\) in \(O(r-l)\) time.

Therefore, the problem has been solved in a total of \(O(|S|^3)\) time.

posted:
last update: