公式

A - Spoon Taking Problem 解説 by evima


[1] Observing the Final Result

The possible ways for everyone to end up taking a spoon are:

  • Everyone takes the spoon on their left side
  • Everyone takes the spoon on their right side

Thus, we should calculate the number of dominant hand combinations that lead to each of these outcomes and sum them up.

[2] Counting

Below, we calculate the number of dominant hand combinations where everyone takes the spoon on their left side. The case where everyone takes the spoon on their right side can be handled similarly.

The strategy involves simulation. Assume that everyone who made the \(1\)-st, \(\dots\), \((i - 1)\)-th actions has taken the spoon on their left side. In the \(i\)-th action, consider whether there are spoons remaining on each side of person \(P_i\). The spoon on the left side of person \(P_i\) is always there, and the spoon on the right side is there if and only if person \((P_i + 1)\) has not acted yet. Here, person \((N + 1)\) refers to person \(1\).

Now that we know which spoons remain when person \(P_i\) acts, we consider the dominant hand of person \(P_i\) that allows them to take the spoon on their left side and count towards the answer. Specifically, we initialize the answer to \(1\) and perform the following process for \(i = 1, \dots, N\) in order while simulating the actions:

  • If the spoon on the right side of person \(P_i\) is remaining:
    • Person \(P_i\) must be left-handed. If the corresponding character in string \(S\) is R, multiply the answer by \(0\); otherwise, do nothing.
  • If the spoon on the right side of person \(P_i\) is not remaining:
    • Person \(P_i\) may be left- or right-handed. If the corresponding character in string \(S\) is ?, multiply the answer by \(2\); otherwise, do nothing.

By performing the above process for the case where everyone takes the spoon on their right side as well and summing up the results, we can solve the problem in \(\mathrm{O}(N)\) time.

Sample Implementation (Python)

投稿日時:
最終更新: