Editorial for Photoshoot


Approach

Look at the lineup in pairs: positions (1,2)(1,2), (3,4)(3,4), and so on. Reversing an even-length prefix never breaks a pair apart; it only reverses the order of the pairs inside the chosen prefix, and each mixed pair flips between GH and HG.

Pairs GG and HH are irrelevant, because they contribute the same number of Guernseys in even positions no matter how many times they are flipped. So only mixed pairs matter:

  • HG is already good, because its even position contains G.
  • GH is bad, because its even position contains H.

Process the pairs from right to left. Suppose we already know how many prefix reversals must affect the suffix to the right. If that count is even, the current mixed pair keeps its type; if it is odd, GH and HG swap roles. That means:

  • when the current pair is GH, we need one more reversal exactly when the current parity is even;
  • when the current pair is HG, we need one more reversal exactly when the current parity is odd.

Pairs with identical letters are skipped. This greedy scan is exactly the official O(N)O(N) solution.

Solution (Python)

Code 1
n = int(input())
s = input().strip()

flips = 0
for i in range(n - 2, -1, -2):
    pair = s[i : i + 2]
    if pair[0] == pair[1]:
        continue
    if (pair == "GH" and flips % 2 == 0) or (pair == "HG" and flips % 2 == 1):
        flips += 1

print(flips)

Comments0


No comments yet

Be the first to comment.

New comment


Log in to join the discussion.