公式

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

swe-2-high

Solution

For each store \(i\), compute the sum of the digits in the string \(S_i\), and answer the index of the store whose sum is the smallest.

Scan the stores in order from \(1\) to \(H\), computing the total sales level sum for each. Keep track of the smallest sum seen so far (bestSum) and the index of the store that achieved it (bestIdx), updating only when sum < bestSum.

Proof of Correctness

  • Loop invariant: after processing store \(i\), bestSum equals the minimum total among stores \(1, \ldots, i\), and bestIdx is the smallest index attaining that minimum.
    • Initially (\(i = 0\)) bestSum is effectively infinity, so the invariant holds vacuously.
    • When store \(i\) has total sum: if sum < bestSum, we update both values; if sum = bestSum, we keep the smaller index bestIdx, preserving the tie-break rule; if sum > bestSum, we do nothing. In all cases the invariant is maintained.
  • Therefore, after all stores are processed, bestIdx is the smallest index among the stores with the minimum total, which is exactly the required output.

Complexity

  • Time: \(O(HW)\), since we scan a string of length \(W\) for each of the \(H\) stores.
  • Space: \(O(W)\) auxiliary space — only one input line is held at a time.

Tie-breaking

Because the update uses a strict < comparison, when multiple stores share the minimum sum the earliest (smallest-numbered) store is retained, satisfying the requirement to output the smallest index.

投稿日時:
最終更新: