A - 果物の選別 / Fruit Sorting 解説 by admin
GPT 5.2 HighOverview
Collect only the fruits with sugar content \(K\) or higher, and compute the average of their sugar content. If there are no such fruits, the average is undefined, so output -1.
Analysis
What we want to find is “the average of elements satisfying the condition (\(S_i \ge K\)).” Since the average can be calculated as: - Total \(\div\) Count
all we need are the total value of fruits satisfying the condition and the count.
For example, when \(N=5, K=10, S=[8,10,12,9,15]\), the fruits that can be shipped are \([10,12,15]\), so: - Total \(= 10+12+15 = 37\) - Count \(= 3\) - Average \(= 37/3\)
Here, we could naively “collect only the qualifying items into a separate list and then take the average,” but since \(N \le 10^6\) is large, creating an extra array wastes memory. Also, in Python, when there is a lot of input, repeatedly calling input() can be slow and often causes TLE.
Therefore, it is safer to update only the total and count in a single loop and read all input at once for speed.
Additionally, if the count of qualifying items is \(0\), we cannot divide by \(0\), so a branch to output -1 is necessary.
Algorithm
- Read \(N, K\) and the array \(S\).
- Initialize
total = 0,cnt = 0. - For each \(x \in S\):
- If \(x \ge K\), then
total += x,cnt += 1
- If \(x \ge K\), then
- If
cnt == 0, output-1. - Otherwise, output the average
total / cnt(floating point is fine since there is an error tolerance).
Complexity
- Time complexity: \(O(N)\) (each element is examined once)
- Space complexity: \(O(1)\) (only a constant number of variables such as total and count)
Implementation Notes
Since the input can have up to \(10^6\) elements, reading all at once with
sys.stdin.buffer.read()is faster.The total can be as large as \(10^6 \times 10^9 = 10^{15}\), but Python integers do not overflow, so this is safe.
For output, using something like
"{:.10f}".format(...)with enough decimal places makes it easy to reliably satisfy the error tolerance of \(10^{-6}\).Source Code
import sys
def main():
data = list(map(int, sys.stdin.buffer.read().split()))
if not data:
return
N, K = data[0], data[1]
S = data[2:2+N]
total = 0
cnt = 0
for x in S:
if x >= K:
total += x
cnt += 1
if cnt == 0:
print(-1)
else:
print("{:.10f}".format(total / cnt))
if __name__ == "__main__":
main()
This editorial was generated by gpt-5.2-high.
投稿日時:
最終更新: