A - 錬金術の材料 / Alchemy Materials Editorial by admin Editorial for printing
swe-2-highSolution
The values are 3 points for gold (G), 2 points for silver (S), and 1 point for copper (C). Therefore, we can obtain the answer by scanning the string \(S\) from left to right and adding the points corresponding to each character.
Concretely, initialize a variable ans to 0, and for each character c of \(S\) do the following:
- If
cisG, add 3 toans - If
cisS, add 2 toans - If
cisC, add 1 toans
Finally, output ans. \(N\) is given as part of the input format, but since a single pass over \(S\) suffices, \(N\) is not needed for the computation itself.
Proof of correctness
The quantity we must compute is “the total value of the materials Takahashi has.” Each material contributes independently, and the value of the \(i\)-th material is determined solely by the \(i\)-th character of \(S\) (G → 3, S → 2, C → 1). Hence the total is
\[\sum_{i=1}^{N} v(S_i)\]
where \(v(\texttt{G})=3\), \(v(\texttt{S})=2\), and \(v(\texttt{C})=1\). The algorithm adds each \(v(S_i)\) exactly once to ans in the order \(i = 1, 2, \dots, N\), so when the loop finishes, ans equals the sum above. By the constraints, every character is one of G, S, C, and all cases are covered by the branches.
Complexity
- Time: \(O(N)\)
- Space: \(O(N)\) (for storing the input string \(S\); auxiliary space excluding input is \(O(1)\))
posted:
last update: