公式

A - 錬金術の材料 / Alchemy Materials 解説 by admin 印刷ページ

gpt-6-astra-medium

Overview

We replace each character in the string \(S\) with the value of its corresponding material and calculate the total sum. G is worth \(3\) points, S is worth \(2\) points, and C is worth \(1\) point.

Analysis

The value of each material depends solely on its type and is not affected by its position or order. Therefore, we can find the answer by traversing the string from the beginning and adding the value of each material.

For example, when \(S =\) GSCG, the total value is: \(3 + 2 + 1 + 3 = 9\) points.

In this problem, a naive approach of checking every character once is fast enough. No special optimizations are needed.

By preparing a dictionary mapping characters to their values, we can look up the value of each material without having to write conditional branches for each type.

Algorithm

  1. Read the number of materials \(N\) and the string \(S\).
  2. Prepare a dictionary value with the following mappings:
    • G: \(3\)
    • S: \(2\)
    • C: \(1\)
  3. For each character c in \(S\), retrieve value[c] and sum them up using sum.
  4. Output the total sum.

Since the value corresponding to each material is added exactly once, the computed total will be the sum of the values of all materials.

Complexity

  • Time complexity: \(O(N)\)
    The string of length \(N\) is traversed once.
  • Space complexity: \(O(N)\)
    Required to store the input string. The auxiliary space complexity excluding the input storage is \(O(1)\).

Implementation Notes

  • value = {'G': 3, 'S': 2, 'C': 1} maps characters to their values.

  • sum(value[c] for c in s) sequentially evaluates the value corresponding to each character and sums them up. Since intermediate values are not stored in a list, it uses only a constant amount of additional memory.

  • Since the length of the string is guaranteed to be \(N\), you do not need to use the input n and can directly iterate over the characters of s.

    Source Code

n = int(input())
s = input()
value = {'G': 3, 'S': 2, 'C': 1}
print(sum(value[c] for c in s))

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

投稿日時:
最終更新: