C - 花壇の植え替え / Replanting the Flower Bed Editorial by admin Editorial for printing
gpt-5.3-codexOverview
To make all plots the same variety, you choose one variety to keep and replant all other plots to that variety.
Therefore, “keeping the most frequently appearing variety and replanting all others” gives the minimum.
Analysis
With the operations, any plot can be freely changed to any variety.
If we fix the final variety to \(x\), the required number of operations is:
- The number of plots that are not originally \(x\)
In other words, [ N \times M - (\text{number of occurrences of variety }x) ]
Since we want to minimize this value, the larger the number of occurrences of \(x\), the better.
Therefore, the answer is
[
N \times M - \max(\text{number of occurrences of each variety})
]
A naive approach of “scanning all cells for each candidate final variety to compute the required number of operations” would be \(O(KNM)\) where \(K\) is the number of varieties, which is inefficient.
Given the constraints \(NM \le 5\times 10^5\), counting frequencies in a single scan is optimal.
For example, if the array is [1, 2, 2, 3, 2, 1] (6 cells total), the maximum occurrence count is 3 for variety 2.
The minimum number of operations is \(6-3=3\).
Algorithm
- Read \(N, M\).
- Use a
Counter(hash map) to count the number of occurrences of each variety number. - Find the maximum occurrence count
max_freq. - Output
N*M - max_freq.
This method is fast because it “looks at each cell only once.”
Complexity
- Time complexity: \(O(NM)\)
- Space complexity: \(O(K)\) (\(K\) is the number of distinct varieties, at most \(NM\))
Implementation Notes
Since variety numbers can be as large as \(10^9\), it is appropriate to use a
Counter(dictionary-based) rather than an array.Because the input size is large,
sys.stdin.readlineis used for fast input.Simply compute
total = N * Mfirst, then outputtotal - max_freqat the end.Source Code
import sys
from collections import Counter
def main():
input = sys.stdin.readline
N, M = map(int, input().split())
total = N * M
cnt = Counter()
for _ in range(N):
row = list(map(int, input().split()))
cnt.update(row)
max_freq = max(cnt.values())
print(total - max_freq)
if __name__ == "__main__":
main()
This editorial was generated by gpt-5.3-codex.
posted:
last update: