PROBLEM LINK:
Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Contest: Division 4
Author: notsoloud
Tester: yash_daga
Editorialist: iceknight1093
DIFFICULTY:
TBD
PREREQUISITES:
None
PROBLEM:
Chef and Chefina play N rounds of standard rock-paper-scissors.
Given Chefina’s moves on all the rounds, find the lexicographically smallest sequence of moves for Chef that allows him to win more than half the games.
EXPLANATION:
The three characters we have to work with are \texttt{P, R, S}.
Among them, \texttt{P} is the smallest, so our aim should be to use it as much as possible.
This can be done greedily.
Let X = \left\lfloor \frac{N}{2} \right\rfloor + 1 be the minimum required number of wins for Chef.
For each i from 1 to N:
- If Chef can play a \texttt{P} at this position, he should.
For this, Chef should be able to win the required number of rounds from the remaining ones.
There are two cases:- First, if A_i = \texttt{R}, then playing \texttt{P} is optimal, since it’s smallest and it wins the round.
So, play it and reduce X by 1 (Chef needs one less win from the remaining rounds). - Otherwise, \texttt{P} here doesn’t lead to a win. Then, Chef can play \texttt{P} here if and only if X \leq N-i: that is, if winning all the rounds after it is enough.
If this condition is true, play \texttt{P}, but don’t reduce X (since Chef doesn’t win this round).
- First, if A_i = \texttt{R}, then playing \texttt{P} is optimal, since it’s smallest and it wins the round.
- If Chef isn’t able to play \texttt{P} at the current position, that means he’s forced to win all his remaining games.
This means all of his remaining moves are uniquely determined - play the only winning move for each of them.
TIME COMPLEXITY:
\mathcal{O}(N) per testcase.
CODE:
Editorialist's code (Python)
win = {'R':'P', 'P':'S', 'S':'R'}
for _ in range(int(input())):
n = int(input())
s = input()
req = n//2 + 1
ans = []
for i in range(n):
if req == n-i:
ans.append(win[s[i]])
req -= 1
else:
ans.append('P')
req -= s[i] == 'R'
print(''.join(ans))