公式

B - 売上の少ない店 / Store with the Lowest Sales 解説 by admin 印刷ページ

gpt-6-astra-medium

Overview

For each store, calculate the sum of the digits contained in the string. Output the store with the smallest store number among those with the minimum sum.

Analysis

Each character in the string represents the sales level for one day. Therefore, instead of converting the entire string into a single integer, we need to convert each character into an integer individually and sum them up.

For example, the sum of sales levels for "203" is not \(203\), but \(2+0+3=5\).

Even if we examine every day for all stores, there are at most \(H \times W = 100\) digits to process. Therefore, a naive approach to calculating the sums will easily run in time, and no optimization is needed.

One thing to be careful about is when multiple stores have the minimum sum. By storing the sums in a list in order of store numbers and finding the first position where the minimum value appears, we can select the store with the smallest store number.

For example, if the list of sums is [5, 3, 3], the minimum value is \(3\), and the answer is the \(2\)-nd store, which appears first.

Algorithm

  1. Read the number of stores \(H\) and the number of days \(W\).
  2. Read the string for each store, convert each character to an integer, and sum them up. Store the results in a list sums in order of store numbers.
  3. Find the minimum sum using min(sums).
  4. Find the first position where this minimum value appears using sums.index(min(sums)).
  5. Since Python lists are \(0\)-indexed, add \(1\) and output the result.

By correctly calculating the sum for each store and selecting the first position of the minimum value, we can obtain the store number that satisfies the conditions, even in the event of a tie.

Complexity

  • Time Complexity: \(O(HW)\)
    Examining \(W\) characters for each store takes \(O(HW)\) time, and finding the minimum value and its position each takes \(O(H)\) time.
  • Space Complexity: \(O(H+W)\)
    The list of sums requires \(O(H)\) space, and the string read for one store requires \(O(W)\) space.

Key Implementation Points

  • sum(int(c) for c in input()) converts each character of the input string to an integer and computes their sum. This correctly handles strings with leading zeros, such as "007".

  • list.index(x) returns the first index where the value x appears. This allows us to select the store with the smallest number in case of a tie.

  • Since store numbers are \(1\)-indexed, do not forget to add + 1 to the retrieved index.

  • Since the length of each string is guaranteed to be \(W\), the code does not need to use w directly and simply traverses the entire string.

    Source Code

# 問題文から独立に実装: 各行の桁の和のリストで最小値の最初の位置
h, w = map(int, input().split())
sums = [sum(int(c) for c in input()) for _ in range(h)]
print(sums.index(min(sums)) + 1)

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

投稿日時:
最終更新: