Official

B - 握手の列 / Line of Handshakes Editorial by admin

Qwen3-Coder-480B

Overview

Participants are standing in a line, and the problem asks us to count the number of adjacent pairs where the glove color of one person’s right hand matches the glove color of the next person’s left hand (an “awkward handshake”).

Analysis

In this problem, for each participant \(i\), we compare the color of their right-hand glove \(R_i\) with the color of the next participant \(i+1\)’s left-hand glove \(L_{i+1}\). If \(R_i = L_{i+1}\), then that pair results in an “awkward handshake.”

A straightforward approach is to perform this comparison for all adjacent pairs. Since the constraint is \(N \leq 2 \times 10^5\), performing all these comparisons is fast enough (see the complexity analysis below).

The key point is that the glove colors are either the character N (navy) or S (white). Since we can simply compare them as characters/strings, no special preprocessing or conversion is needed.

Algorithm

  1. Read the glove information for each participant and store it in a list or similar data structure.
  2. For each adjacent pair \((i, i+1)\), check whether participant \(i\)’s right-hand color \(R_i\) is equal to participant \(i+1\)’s left-hand color \(L_{i+1}\).
  3. If they are equal, increment the count.
  4. Output the final count.

Complexity

  • Time complexity: \(O(N)\)
  • Space complexity: \(O(N)\)

The time complexity is linear because we examine each adjacent pair exactly once. The space complexity requires storing data for all \(N\) participants.

Implementation Notes

  • Glove colors can be handled as strings, so direct comparison works fine.

  • The input is in a format like "N S", so you can easily extract the left and right colors using split().

  • Be careful about out-of-bounds index access (since the last participant has no next person, the loop should run from \(i = 0\) to \(N-2\)).

    Source Code

N = int(input())
gloves = [input().split() for _ in range(N)]

count = 0
for i in range(N - 1):
    if gloves[i][1] == gloves[i + 1][0]:
        count += 1

print(count)

This editorial was generated by qwen3-coder-480b.

posted:
last update: