A - 果物の選別 / Fruit Sorting Editorial by admin
DeepSeek V3Overview
This is a problem where you select only fruits with a sugar content of \(K\) or more and find their average value. If no fruits satisfy the condition, output -1.
Analysis
This problem is a simple filtering problem where you select elements from a list of fruit sugar contents that satisfy a condition and calculate their average. The two important points are:
- Condition checking: Determine whether each fruit’s sugar content \(S_i\) is \(K\) or more
- Average calculation: Maintain the sum and count of sugar contents of fruits that satisfy the condition, and calculate the average
A straightforward approach is to read all fruits at once, select only those that meet the condition, and perform the calculation. From the constraints, \(N\) can be up to \(10^6\), but a simple linear scan is sufficient to handle this.
Algorithm
- Read \(N\), \(K\), and the sugar content list \(S_1, S_2, ..., S_N\) from input
- Initialize the sum
totaland countcountto 0 - For each sugar content \(S_i\):
- If \(S_i \geq K\), add \(S_i\) to
totaland incrementcountby 1
- If \(S_i \geq K\), add \(S_i\) to
- If
countis 0, output -1 - Otherwise, calculate
total / countand output it to 10 decimal places
Complexity
- Time complexity: \(O(N)\)
- Because a comparison operation is performed once for each of the \(N\) elements
- Space complexity: \(O(N)\)
- Memory is needed to store the sugar content list
Implementation Notes
Efficient input handling: Use
sys.stdin.read()to efficiently process large amounts of input dataPrecision handling: Specify up to 10 decimal places for the average output to satisfy the error requirements
Division by zero avoidance: Explicitly check the case where 0 fruits satisfy the condition
Memory efficiency: Instead of storing all qualifying fruits in a separate list, only maintain the sum and count to minimize memory usage
Source Code
def main():
import sys
data = sys.stdin.read().split()
n = int(data[0])
K = int(data[1])
S_list = list(map(int, data[2:2+n]))
total = 0
count = 0
for s in S_list:
if s >= K:
total += s
count += 1
if count == 0:
print(-1)
else:
average = total / count
print("{:.10f}".format(average))
if __name__ == "__main__":
main()
This editorial was generated by deepseekv3.
posted:
last update: