公式

A - アルファベット分類 / Alphabet Classification 解説 by admin

Gemini 3.0 Flash (Thinking)

Overview

This is a problem where you group \(N\) strings by their first character and find the size of the group that contains the most strings.

Analysis

The key observations for this problem are: “You can ignore everything from the 2nd character onward in each string” and “There are only 26 possible groups, corresponding to the lowercase English letters ‘a’ through ‘z’.”

For example, if the input is apple, ant, banana: - Group starting with ‘a’: apple, ant (2 strings) - Group starting with ‘b’: banana (1 string)

So the maximum is 2.

Even if the same string appears multiple times, each occurrence is counted individually. Therefore, you simply need to check only the first character of each string and count the number of occurrences.

Algorithm

  1. Since there are 26 lowercase English letters, prepare an array of length 26 (or a hash map/dictionary) to record the occurrence count of each character.
  2. For each of the \(N\) given strings \(S_i\), repeat the following operations:
    • Extract the first character of \(S_i\).
    • Increment the count in the array corresponding to that character by 1.
  3. Output the maximum value in the array.

To convert a character to an array index (0–25), it is convenient to use the ord function (a function that returns the character code), which is available in many programming languages. By computing ord(first_character) - ord('a'), you can obtain the values 0 for ‘a’, 1 for ‘b’, …, and 25 for ‘z’.

Complexity

  • Time complexity: \(O(N)\)
    • Since we scan each of the \(N\) strings once, the processing completes in time proportional to the number of strings \(N\).
  • Space complexity: \(O(N + |\Sigma|)\)
    • \(O(N \times (\text{string length}))\) is needed to store the input strings, and an array of size \(|\Sigma| = 26\) (the number of distinct characters) is needed for counting occurrences.

Implementation Tips

  • Fast I/O: Since \(N\) can be as large as \(10^5\), which is relatively large, in Python you can reduce execution time by reading all input at once using sys.stdin.read().split() or similar methods.

  • Index calculation: By using ord(first_char) - ord('a'), you can directly use alphabet letters as array indices.

  • Handling duplicates: Since the problem states that you should count without removing duplicates, there is no need to use a set or similar structure to obtain unique strings. Simply count all occurrences.

    Source Code

import sys

def solve():
    input_data = sys.stdin.read().split()
    if not input_data:
        return
    
    n = int(input_data[0])
    strings = input_data[1:]
    
    counts = [0] * 26
    offset = ord('a')
    
    for i in range(n):
        first_char = strings[i][0]
        counts[ord(first_char) - offset] += 1
        
    print(max(counts))

if __name__ == "__main__":
    solve()

This editorial was generated by gemini-3-flash-thinking.

投稿日時:
最終更新: