公式

A - 招待状の宛名書き / Addressing Wedding Invitations 解説 by admin

Qwen3-Coder-480B

Overview

A problem where you attach honorifics based on participants’ titles and output them sorted in a specific group order.

Analysis

In this problem, you need to classify participants into two groups and rearrange them while preserving the original order within each group.

  • Group A: Title is teacher or doctor → Honorific is sensei
  • Group B: Title is student or other → Honorific is san

The key point is the condition “preserve input order within the same group.” In other words, if you simply sort, this order might break.

For example, consider the following input:

3
alice student
bob teacher
charlie doctor

The correct output is:

bob sensei
charlie sensei
alice san

bob and charlie are in Group A, and alice is in Group B. Within Group A, bobcharlie was the input order, so this order must be preserved.

Therefore, the best approach is as follows:

  1. Read the input sequentially and assign each participant to Group A or Group B
  2. Concatenate the Group B list after the Group A list
  3. Output each person with their honorific in order

With this method, the order within each group is maintained, and the overall order is also correct.

Algorithm

  1. Store all participant information in a list.
  2. Look at each participant’s title and assign them to Group A or Group B.
  3. Concatenate Group A and Group B to create a new list.
  4. Output each person in the new list with their honorific attached.

Complexity

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

※ Since we only look at each element once and perform list appending, concatenation, and output, the processing can be done in linear time.

Implementation Notes

  • Managing each participant’s information as a (name, title) tuple makes it easy to handle.

  • Performing the honorific conversion at output time keeps the code simple.

  • To preserve input order, use list append and ensure concatenation also maintains order.

    Source Code

N = int(input())
participants = []
for _ in range(N):
    s, r = input().split()
    participants.append((s, r))

group_A = []
group_B = []

for s, r in participants:
    if r in ('teacher', 'doctor'):
        group_A.append((s, r))
    else:
        group_B.append((s, r))

result = group_A + group_B

for s, r in result:
    if r in ('teacher', 'doctor'):
        print(s, 'sensei')
    else:
        print(s, 'san')

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

投稿日時:
最終更新: