A - 果物の選別 / Fruit Sorting 解説 by admin
Qwen3-Coder-480BOverview
Given the sugar content of fruits, select only those with sugar content at least the threshold \(K\), and find their average value.
Analysis
In this problem, we need to select all fruits with sugar content \(K\) or higher, and calculate their average.
If there are no such fruits, output -1.
A straightforward approach is to examine all fruits and add those satisfying the condition to a separate list. This method is sufficiently fast since it only checks each fruit once. Even in the worst case, \(N = 10^6\), and simply examining each element once is well within the capabilities of modern computers.
Also, when calculating the average, since we are dividing integers, the result needs to be a floating-point type (float in Python).
There are constraints on error tolerance, but Python’s standard division uses double-precision, which is well within the acceptable range.
Algorithm
- Read \(N\), \(K\), and the list of sugar content values \(S\) from the input.
- Using list comprehension or similar, extract only the elements satisfying \(S_i \geq K\) into a new list
shipping_sugar. - If
shipping_sugaris empty, output-1. - If it is not empty, calculate the average using
sum(shipping_sugar) / len(shipping_sugar)and output it.
For example, given the following input:
5 3
1 4 2 5 3
The fruits with sugar content 3 or higher are [4, 5, 3], and their average is \((4 + 5 + 3)/3 = 4.0\).
Complexity
- Time complexity: \(O(N)\) (Scan each element once for filtering, then compute the sum and count)
- Space complexity: \(O(N)\) (A new list is created to store the elements satisfying the condition)
Implementation Notes
Extracting elements that satisfy the condition can be written concisely using list comprehension.
When calculating the average directly from the sum and count, care must be taken to avoid division by zero, but in this case it is safe since we check whether there are qualifying elements beforehand.
There are no particular restrictions on the output format, and outputting as a floating-point number is acceptable.
Source Code
N, K = map(int, input().split())
S = list(map(int, input().split()))
# 出荷可能な果物の糖度を抽出
shipping_sugar = [s for s in S if s >= K]
# 出荷可能な果物がなければ -1 を出力
if not shipping_sugar:
print(-1)
else:
# 平均値を計算して出力
average = sum(shipping_sugar) / len(shipping_sugar)
print(average)
This editorial was generated by qwen3-coder-480b.
投稿日時:
最終更新: