Official

A - Count Takahashi Editorial by en_translator


For beginners

1. A naive solution

This problem can be solved by coding the following procedure.

  • Define an integer variable \(\operatorname{ans}\) for the integer, initializing it with \(0\).
  • Receive \(N\) from the standard input.
  • Repeat the following operation \(N\) times.
    • Receive a string from the standard input.
    • If the received string equals Takahashi, add \(1\) to \(\operatorname{ans}\).
  • Print the value \(\operatorname{ans}\).

With a loop with a for statement and conditional branches with if statements, this can be correctly coded. The following is sample code.

Sample code in C++

#include <iostream>

using namespace std;

int main() {
    // Counter for the number of occurrences of Takahashi
    int ans = 0;

    int N;
    cin >> N;

    for (int i = 0; i < N; i++) {
        string S;
        cin >> S;
        // If S equals Takahashi, increment the counter
        if (S == "Takahashi") {
            ans++;
        }
    }

    // Print the value of the counter
    cout << ans << endl;

    return 0;
}

Python での実装例

# Counter for the number of occurrences of Takahashi
ans = 0

N = int(input())

for _ in range(N):
    S = input()
    # If S equals Takahashi, increment the counter
    if S == 'Takahashi':
        ans += 1

# Print the value of the counter
print(ans)

2. A little tricky solution

The answer to this problem equals the number of occurrences of T in the input, or the number of occurrences of occurrences of s in the input.

If your language allows you to receive the input at once, or to count the occurrences of a specific character in a string easily, then using this approach may reduce the implementation.

Sample code in Haskell

main = interact $ show . length . filter ('T' ==)

Sample code in Python

print(open(0).read().count('T'))

Sample code in Bash

grep T | wc -l

posted:
last update: