公式
B - 握手の列 / Line of Handshakes 解説 by admin
Claude 4.5 OpusOverview
When \(N\) people are standing in a line, this problem asks us to count the number of pairs where adjacent people have an “awkward handshake” (gloves of the same color) when shaking hands.
Analysis
Understanding the Problem
First, let’s organize the problem statement.
- When participant \(i\) and participant \(i+1\) shake hands, participant \(i\)’s right hand and participant \(i+1\)’s left hand touch each other
- If the touching gloves are the same color, it’s an “awkward handshake”
- We count the number of awkward handshakes for all pairs where \(i = 1, 2, \ldots, N-1\)
Thinking Through a Concrete Example
For example, suppose there are 3 participants wearing gloves as follows:
| Participant | Left hand (\(L_i\)) | Right hand (\(R_i\)) |
|---|---|---|
| 1 | N | S |
| 2 | S | N |
| 3 | N | S |
- Handshake between participant 1 and participant 2: Participant 1’s right hand (S) vs Participant 2’s left hand (S) → Same color → Awkward handshake
- Handshake between participant 2 and participant 3: Participant 2’s right hand (N) vs Participant 3’s left hand (N) → Same color → Awkward handshake
The answer is \(2\).
A Naive Approach Is Sufficient
In this problem, for each of the \(N-1\) adjacent pairs, we only need to compare the glove colors once. No special techniques are needed, and it can be solved in \(O(N)\) with a simple loop.
Algorithm
- Read the glove information (left hand \(L_i\), right hand \(R_i\)) for \(N\) people and store them in an array
- Initialize a counter
countto \(0\) - For \(i = 0, 1, \ldots, N-2\) (0-indexed):
- Compare participant \(i\)’s right hand color
gloves[i][1]with participant \(i+1\)’s left hand colorgloves[i+1][0] - If they are the same color, increment
countby \(1\)
- Compare participant \(i\)’s right hand color
- Output
count
Complexity
- Time complexity: \(O(N)\)
- \(O(N)\) for reading input
- \(O(N-1) = O(N)\) for comparing pairs
- Space complexity: \(O(N)\)
- For storing all participants’ glove information in an array
Implementation Notes
- In Python, you can read the left and right hand colors at once using
input().split() - Pay attention to array indexing: the code uses 0-indexed, so participant \(i\) (1-indexed) corresponds to index \(i-1\)
- Comparison can be done with simple string comparison
==('N' == 'N'isTrue,'N' == 'S'isFalse)
Source Code
n = int(input())
gloves = []
for _ in range(n):
l, r = input().split()
gloves.append((l, r))
count = 0
for i in range(n - 1):
# Compare participant i's right hand with participant i+1's left hand
if gloves[i][1] == gloves[i + 1][0]:
count += 1
print(count)
This editorial was generated by claude4.5opus.
投稿日時:
最終更新: