Official

A - 旅の記録 / Travel Records Editorial by admin Editorial for printing

gpt-6-astra-medium

Overview

Iterate through the string \(S\) from the beginning and count the number of uppercase English letters. This is the number of times Takahashi visited a foreign country.

Analysis

According to the problem statement, uppercase English letters represent visits to foreign countries, and lowercase English letters represent visits to domestic prefectures. Therefore, we just need to check whether each character is an uppercase English letter, and if it is uppercase, add \(1\) to the answer.

For example, if \(S =\) AbCaA, the uppercase letters are A, C, and A, which makes \(3\) in total, so the answer is \(3\).

Note that what we want to find is the “number of visits”, not the “number of distinct countries”. Even if the same uppercase letter appears multiple times, we count it each time. Be careful not to remove duplicates using a set or similar data structure, as that will lead to an incorrect answer.

In this problem, naively checking all characters is sufficient. Since the length of the string is at most \(100\), there is no need to make any special optimizations regarding the time limit.

Algorithm

  1. Read \(N\) and the string \(S\) from the input.
  2. For each character in \(S\), check whether it is an uppercase English letter.
  3. Print the number of uppercase English letters.

In the reference solution, both the condition check and counting are done concisely using the following expression:

sum(1 for c in s if c.isupper())

c.isupper() returns True if the character c is uppercase. This expression yields a \(1\) whenever an uppercase letter is found, and sum() totals them up.

Since each character is examined exactly once and \(1\) is added only when it is uppercase, we obtain the desired number of uppercase letters.

Complexity

  • Time complexity: \(O(N)\)
  • Space complexity: \(O(N)\) (including storing the input string; the additional space used for counting is \(O(1)\))

Implementation Notes

  • Since \(S\) consists only of uppercase and lowercase English letters, we can check them using isupper().

  • If there are no uppercase letters, the result of sum() will be \(0\), which can be printed correctly as is.

  • Although \(N\) is read from the input in the code, it is not used in the subsequent processing because the string is iterated over directly.

  • Using a generator expression allows counting without creating an intermediate list.

    Source Code

# 問題文から独立に実装
n = int(input())
s = input().strip()
print(sum(1 for c in s if c.isupper()))

This editorial was generated by gpt-6-astra-medium.

posted:
last update: