公式

A - 果物の選別 / Fruit Sorting 解説 by admin

DeepSeek V3

Overview

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:

  1. Condition checking: Determine whether each fruit’s sugar content \(S_i\) is \(K\) or more
  2. 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

  1. Read \(N\), \(K\), and the sugar content list \(S_1, S_2, ..., S_N\) from input
  2. Initialize the sum total and count count to 0
  3. For each sugar content \(S_i\):
    • If \(S_i \geq K\), add \(S_i\) to total and increment count by 1
  4. If count is 0, output -1
  5. Otherwise, calculate total / count and 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 data

  • Precision 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.

投稿日時:
最終更新: