E - Yin-Yang Two Bits Insertion 解説 by evima
Define:
\(A'_i = \begin{cases} 0 & (A_i = A_{i+1}) \\ 1 & (A_i \neq A_{i+1}) \end{cases}\).
Define \(B'\) similarly. The operation corresponds to performing one of the following on \(A'\):
- Change \(0\) to \(101\).
- Change \(1\) to \(111\).
The operation leaves the first character, the last character, and the number of \(0\)s in \(A'\) all unchanged, so if these differ, the answer is No.
Assume they are equal.
Split \(A'\) by \(0\)s and consider how many \(1\)s are in each segment.
Then the operation corresponds to:
- Add \(1\) to two adjacent terms.
- Add \(2\) to a term that is at least \(1\).
When the first operation is applied to the same pair of adjacent terms three or more times, two of those applications can be replaced by the second operation. Thus, we may assume the first operation is applied to any given pair of adjacent terms at most twice. We can compute by DP, going through the sequence from left to right, using the number of times the first operation was applied to the immediately preceding pair of adjacent terms as the key to determine whether each state is reachable. The time complexity is \(O(|A| + |B|)\).