D - ABC Ultimatum Editorial by antontrygubO_o
Let \(f_{AB}(i)\) be the number of B
s minus the number of A
s among the first \(i\) characters of the string, and let’s define \(M_A = max(f_{AB}(0), f_{AB}(1), \ldots, f_{AB}(3N))\). Let’s define \(f_{BC}\) and \(f_{CA}\) similarly, and \(M_B = max(f_{BC}(0), f_{BC}(1), \ldots, f_{BC}(3N))\), \(M_C = max(f_{CA}(0), f_{CA}(1), \ldots, f_{CA}(3N))\).
We will prove that it’s possible to split the string \(T\) into such \(N\) subsequences if and only if \(M_A+M_B+M_C\le N\).
Necessity: If there exists such splitting, then \(M_A+M_B+M_C\le N\).
Suppose that we have managed to split our string into \(A_1\) subsequences ABC
, \(B_1\) subsequences BCA
, \(C_1\) subsequences CAB
. Then the balance \(M_A\) can’t be worse than \(B_1\), as in subsequences ABC
and CAB
A
goes before B
. Similarly, the balance \(M_B\) can’t be worse than \(C_1\), and balance \(M_C\) can’t be worse than \(C_1\), so \(M_A+M_B+M_C\le A_1 + B_1 + C_1 = N\).
Sufficiency: If \(M_A+M_B+M_C\le N\), we can split letters into triples (\(i\)-th A
, \((i+M_A)\)-thB
, \((i+M_A+M_B)\)-th C
) (here \(i+N\)-th letter \(X\) denotes \(i\)-th letter \(X\), meaning that we enumerate cyclically).
Let’s consider string \(S+S+S\). Note that in it for any \(i\le 2N\), \(i\)-th A
goes before \(i+M_A\)-th B
, \(i\)-th B
goes before \(i+M_B\)-th C
, \(i\)-th C
goes before \(i+M_C\)-th A
(from the balance logic). This means that \(i\)-th A
goes before the \(i+M_A\)-th B
, which goes before the \(i+M_A+M_B\)-th C
, which goes before the \(i+M_A+M_B+M_C\)-th A
, which coincides or goes before to \(i+N\)-th A
. This clearly means that \(i\)-th A
, \((i+M_A)\)-thB
, \((i+M_A+M_B)\)-th C
go in the cyclic order in the string, so the matching is valid.
With this observation, writing \(O(N^6)\) dp is trivial: just keep track of how many letters A
, B
, C
we have already taken, and the max values of \(f_{AB}(i), f_{BC}(i), f_{CA}(i)\) so far. At first sight, it’s \(O(N^7)\), but the total number of characters after processing \(i\)-th one has to be \(i\), so it’s still \(O(N^6)\) with an extremely small constant (the solution would work for \(N\le 40\) as well).
Bonus: What if the problem is about splitting string of \(N\) A
s, \(N\) B
s, \(N\) C
s, \(N\) D
s into subsequences ABCD
, BCDA
, CDAB
, DABC
?
posted:
last update: