E - I hate ABC Editorial by evima
For simplicity, replace \(K\) with \(N-K\). Here, the condition is equivalent to “the maximum number of ABCs that can be taken independently from subsequences is \(K\)”. The proof follows from the fact that both “the minimum number of characters that need to be deleted from string \(S\) to make it impossible to take ABC as a subsequence” and “the maximum number of ABCs that can be taken independently from string \(S\)” are computed by the following code:
int A=0,AB=0,ABC=0;
for(int i=0;i<S.size();i++){
if(S[i]=='A') A++;
if(S[i]=='B') AB=min(AB+1,A);
if(S[i]=='C') ABC=min(ABC+1,AB);
}
Hereafter, we consider counting strings from which \(K\) ABCs can be taken independently. (It is allowed to take \(K+1\) or more.) Also, replace \(N\) with \(N-3K\). Here, when we see string \(S\), consider greedily taking \(K\) independent ABCs from the front. Then, a string with \(K\) ABCs mixed in appears. For example,
ABABCBAACcan greedily yield twoABCs at positions \(1,2,5\) and \(3,4,9\), and extracting only these parts from the original string givesABABCC.
Let’s count by fixing such strings. Then, we insert a total of \(N\) characters between each character (or at the beginning or end), and for each gap, the number of different characters that can be inserted is \(0\), \(1\), \(2\), or \(3\). Therefore, it has a representation as a generating function \(\frac{1}{(1-x)^p(1-2x)^q(1-3x)^r}\).
Consider taking the sum of this generating function over all strings that can result from the greedy process consisting of \(K\) ABCs. Then, we can easily see that \(p \le 3K,q \le 3K,r = 1\), so the sum has the representation \(\frac{f(x)}{(1-x)^{3K}(1-2x)^{3K}(1-3x)}\). (\(p\) and \(q\) can have better upper bounds by a constant factor, but we omit this.) \(f(x)\) can also be obtained directly by DP, but we can also perform DP with keys i, A, AB, ABC from the above code, obtain the leading terms, and reconstruct \(f(x)\) from them. The computational complexity of this part is \(\mathrm{O}(K^4)\).
To answer each query, we maintain the partial fraction decomposition result \(\frac{f(x)}{(1-x)^{3K}(1-2x)^{3K}(1-3x)} = \frac{f_1(x)}{(1-x)^{3K}} + \frac{f_2(x)}{(1-2x)^{3K}} + \frac{f_3(x)}{1-3x}\). In partial fraction decomposition, we want to obtain \(g(x)\) satisfying \(g(x)(1-2x)^n= 1 \bmod (1-x)^m\), etc., which can be done by performing the Euclidean algorithm for polynomials, or by substituting \(y = 1-x\), transforming to \(g(x)(-1+2y)^n = 1 \bmod y^m\), expressing \(g(x) = (-1+2y)^{-n}\) as a polynomial of degree \(m\) in \(y\), and then converting the variables back, etc.
Once partial fraction decomposition is done, it is easy to answer each query in \(\mathrm{O}(K)\). Therefore, we can solve this problem in \(\mathrm{O}(K^4 + QK)\). (Precomputing binomial coefficients in \(\mathrm{O}(N+K)\) is also allowed.)
posted:
last update: