Official
B - 売上の少ない店 / Store with the Lowest Sales Editorial by admin
swe-2-highSolution
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\),
bestSumequals the minimum total among stores \(1, \ldots, i\), andbestIdxis the smallest index attaining that minimum.- Initially (\(i = 0\))
bestSumis effectively infinity, so the invariant holds vacuously. - When store \(i\) has total
sum: ifsum < bestSum, we update both values; ifsum = bestSum, we keep the smaller indexbestIdx, preserving the tie-break rule; ifsum > bestSum, we do nothing. In all cases the invariant is maintained.
- Initially (\(i = 0\))
- Therefore, after all stores are processed,
bestIdxis 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.