A - りんごの重さ調整 / Adjusting the Weight of Apples Editorial by admin
Qwen3-Coder-480BOverview
This is a problem of minimizing the total amount shaved off to make all apples weigh the same after coating.
Analysis
Each apple is coated with \(R\) grams, so apple \(i\) weighs \(A_i + R\). Takahashi’s goal is to make all apples weigh the same value \(X\). However, he can only shave off weight — he cannot increase the weight.
Here is a key observation: To minimize the total amount shaved, it is optimal to match all apples’ weights to “the weight of the lightest apple.”
This is because if the target weight \(X\) is lighter than “the weight of the lightest apple,” that apple cannot reach the target (since we can only shave off weight). Also, if \(X\) is heavier than “the weight of the lightest apple,” the overall amount shaved increases, which is inefficient.
Therefore, we find the minimum among the list of weights after coating \([A_1 + R, A_2 + R, ..., A_N + R]\), and optimally shave all other apples down to that minimum.
For example, if \(A = [3, 1, 4], R = 2\): - After coating: \([5, 3, 6]\) - The minimum is 3 - Amount shaved: \((5-3) + (3-3) + (6-3) = 2 + 0 + 3 = 5\)
This way, the total amount shaved is minimized.
Algorithm
- Calculate each apple’s weight after coating: \(A_i + R\)
- Find the minimum among them
- Sum up the difference between each apple’s weight and the minimum
This sum is the answer.
Complexity
- Time complexity: \(O(N)\)
- Space complexity: \(O(N)\)
(Because we create a list of weights. It is also possible to reduce space complexity to \(O(1)\) if needed.)
Implementation Notes
- Read input efficiently (using
sys.stdin.read) - Add \(R\) to each apple’s weight to create a list
- Find the minimum and sum up the differences from it
## Source Code
```python
import sys
input = sys.stdin.read
def main():
data = input().split()
N = int(data[0])
R = int(data[1])
A = list(map(int, data[2:]))
# コーティング後の重さ
coated_weights = [a + R for a in A]
# 最小の重さに合わせるのが最適
min_weight = min(coated_weights)
# 削る量の合計
total_cut = sum(w - min_weight for w in coated_weights)
print(total_cut)
if __name__ == "__main__":
main()
This editorial was generated by qwen3-coder-480b.
posted:
last update: