Official

B - Self Checkout Editorial by ebi_fly


Problem Explanation

For a sequence \(S\) that results in a non-zero answer, the sequence of elements in \(S\) can be represented using a regular expression as \((3*2)*3*2*1?\), where \(*\) denotes zero or more repetitions of the preceding element and \(?\) denotes zero or one occurence of the preceding element.

Let’s analyze simpler cases step by step.


Case 1: \(S = 3*\)

If \(S\) is \(3*\) and the number of \(3\)’s is \(p\), then sequences of \(1\) and \(2\) that generate \(S\) satisfy the following conditions:

  1. The sequence contains \(p\) \(1\)’s and \(p\) \(2\)’s.
  2. At any point, the prefix sum of \(1\)’s does not exceed the prefix sum of \(2\)’s by more than \(1\).

The total number of such sequences is equivalent to the number of shortest paths from \((0, 0)\) to \((p, p)\) that stay above the line \(y = x + 1\). This is given by:

\[ \binom{2p}{p} - \binom{2p}{p+2}. \]


Case 2: \(S = 3*2*1?\)

Sequences generating \(3*2*1?\) depend on how \(2\)’s are formed:

  1. Removing two \(1\)’s to generate a \(2\).
  2. Removing one \(2\) to generate another \(2\).

Additionally, the sequences generating \(3*\) form the prefix of the sequences generating \(S\).

Case 2.1: When the Sequence Ends with \(1\)

If the sequence ends with \(1\), all \(2\)’s must be formed by removing two \(1\)’s. Thus, generating \(2*\) only requires appending the necessary \(1\)’s to the sequence generating \(3*\).

Case 2.2: When the Sequence Ends without \(1\)

If the sequence ends with \(q\) consecutive \(2\)’s:

  • The first \(i\) \(2\)’s are generated by removing two \(1\)’s each.
  • The remaining \(q-i\) \(2\)’s are generated by removing one \(2\) each.

For \(i > 0\), the suffix of the sequence consists of \(2i\) \(1\)’s followed by \(q-i\) \(2\)’s.
For \(i = 0\), the total number of \(2\)’s increases by \(q\).

The count of such sequences corresponds to the number of shortest paths from \((0, 0)\) to \((p+q, p)\) that stay above \(y = x + 1\), calculated as:

\[ \binom{2p + q}{p} - \binom{2p + q}{p + q + 2}. \]

Case 3:\(S = (3*2)3*2*1?\)

Now consider the case where \(S\) cannot be represented as \(3*2*1?\).

The subsequence generating \((3*2)\) is constructed by appending two 1s to the end of the sequence that generates \(3*\). Since there are two consecutive 1s at the end of this part, the subsequences generating \((3*2)\) and \(3*2*1?\) are disjoint, non-overlapping contiguous subsequences.

Therefore, they can be independently counted, and the product of the counts gives the total.


Case 4: \(S = (3*2)*3*2*1?\)

Similarly, in the sequence \(A\), each \((3*2)\) and \(3*2*1?\) corresponds to distinct, non-overlapping contiguous subsequences. Therefore, they can also be independently counted, and the results multiplied.


Conclusion

Using the above breakdown, the problem can be solved efficiently in \(O(N)\).

posted:
last update: