公式

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

GPT 5.2 High

Overview

We only consider fruits with a sugar content of \(K\) or more, and compute the average of their sugar contents. If there are no such fruits, we output -1.

Analysis

The key insight is that since “the average is computed as \(\text{total} / \text{count}\)”, it is sufficient to know only the total and count of the fruits eligible for shipment.

  • For example, when \(S=[3,7,8,2],\ K=6\), the eligible fruits are \(7,8\), so the total is \(15\), the count is \(2\), and the average is \(7.5\).
  • In the case where there are no eligible fruits (e.g., all are less than \(K\)), division cannot be performed, so we specially output -1.

Also, since the constraint \(N \le 10^6\) is large, naive approaches such as: - Collecting eligible fruits into an array and then computing the average (requires extra memory) - Reading standard input in a slow manner for large inputs (easily causes TLE in Python)

are disadvantageous. Therefore, we use a method that accumulates the total and count of only the elements satisfying the condition while reading (single pass). Furthermore, to speed up input, we read everything at once with sys.stdin.buffer.read() and parse the integers ourselves.

Algorithm

  1. Prepare \(total=0\) (sum of sugar contents of eligible fruits) and \(cnt=0\) (count of eligible fruits).
  2. For \(i=1..N\), read sugar content \(S_i\).
    • If \(S_i \ge K\), then \(total \leftarrow total + S_i\), \(cnt \leftarrow cnt + 1\).
  3. After the scan:
    • If \(cnt=0\), output -1.
    • Otherwise, output the average \(total/cnt\) with sufficient precision (in this code, 10 decimal places).

Complexity

  • Time complexity: \(O(N)\) (each fruit is examined exactly once)
  • Space complexity: \(O(1)\) (only a constant number of variables such as total and count; excluding the bulk input read buffer)

Implementation Notes

  • Always check \(cnt=0\) before division (to prevent division by zero and output -1 as specified).

  • Since there is an error tolerance for the average, outputting with a sufficient number of digits such as {:.10f} is safe.

  • Since \(N\) is large, input/output tends to be a bottleneck in Python. Reading integers quickly using sys.stdin.buffer.read() with a custom parser, as in this code, ensures stable performance.

    Source Code

import sys

data = sys.stdin.buffer.read()
n = len(data)
idx = 0

def next_int():
    global idx
    while idx < n and data[idx] <= 32:
        idx += 1
    num = 0
    while idx < n and data[idx] > 32:
        num = num * 10 + (data[idx] - 48)
        idx += 1
    return num

N = next_int()
K = next_int()

total = 0
cnt = 0
for _ in range(N):
    s = next_int()
    if s >= K:
        total += s
        cnt += 1

if cnt == 0:
    sys.stdout.write("-1")
else:
    sys.stdout.write("{:.10f}".format(total / cnt))

This editorial was generated by gpt-5.2-high.

投稿日時:
最終更新: