Official Analysis (C++)

Video Solution

Note: The video solution might not be the same as other solutions. Code in C++.

Solution

The main observation for this problem is that we only need to keep track of the number of games played ii, the number of times switched so far jj, and the current gesture kk in order to determine the largest number of previous games won for any game ii.

For every move, either Bessie can either switch or stay on her current gesture. If she changes her gesture, then the next game i+1i+1 will have used j+1j+1 gestures, which corresponds to the dp\texttt{dp} state dp[i+1][j+1][k]\texttt{dp}[i+1][j+1][k]. We can simulate this for all 3 gestures. Then, we just increment dp[i][j][k]\texttt{dp}[i][j][k] if Bessie wins at game ii with gesture kk.

Note that you can just compare the current gesture to H, P, S because there is always exactly one way to win.

Time Complexity: O(NK)\mathcal{O}(NK)

Warning!

Due to Python's constant factor, the below solution TLEs on a couple test cases.

with open("hps.in") as read:
n, k = map(int, read.readline().strip().split())
moves = [0] * n
for i in range(n):
a = read.readline().strip()
if a == "H":
moves[i] = 0
elif a == "P":
moves[i] = 1
else:

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!