Official

H - Alphabet Tiles Editorial by en_translator


As in the problem statement, let \(a_i\) be the \(a_i\)-th capital English letter.

Consider counting conforming strings for each number of occurrences of z, and finding the answer as their sum. (For convenience we take a letter z, but this is not essential; you can fix any letter and find the count for each number of its occurrences.)

Suppose that a length-\(s\) string has \(t\) occurrences of z. Then, there are \(\binom{s}{t}\) ways to determine the positions of z. The characters at the other positions form a string of length \((s-t)\) without z such that \(a_i\) occurs between \(0\) and \(C_i\) times, which is understood by considering the string of length \((s-t)\) obtained by removing z, for each of the \(\binom{s}{t}\) positions.

Therefore, the problem for a, b, \(\ldots\), z has been boiled down to that fora, b, \(\ldots\), y.

Similarly, the problem for a, b, \(\ldots\), y can be boiled down to that for a, b, \(\ldots\), x; repeating this procedure seems to solve the problem.

Once you boiled down the problem with a smaller one, employing DP (Dynamic Programming) is often effective.

Indeed, let \(dp_{i,j}\) be the number of length-\(j\) strings consisting of \(a_1, a_2, \ldots, a_i\) such that \(a_k\) occurs between \(0\) and \(C_k\) times for all \(1 \leq k \leq i\); then by the observation above it turns out that \(dp_{i + 1, j} = \sum_{k = 0}^{\min(j, C_{i+1})} dp_{i,j-k} \binom{j}{k}\). (We find the sum over \(k\), the number of occurrences of \(a_{i + 1}\).)

The answer is \(\sum_{j= 1}^{K}dp_{26, j}\). Note that the DP only ranges in \(j \leq K\).

By finding the binomial coefficients according to precalculated factorials and it inverses, or by precomputing the binomial coefficients themselves in the manner of Pascal’s triangle,this DP can be solved in a total of \(O(\sigma K^2)\) time, where \(\sigma\) is the size of alphabet (\(\sigma = 26\) in our case), which is fast enough for the constraints for this problem.

Sample code (C++)

posted:
last update: