Official

B - 果物の選別 / Fruit Sorting Editorial by admin

GPT 5.2 High

Overview

Among the fruits with blemishes, count only those with sweetness less than \(K\), and find the count and total sweetness.

Analysis

What we want to find are the “substandard products” = fruits that are (blemished) AND (sweetness less than \(K\)).
In other words, it suffices to focus only on the list of blemished fruit numbers \(B_1,\dots,B_M\), check each of their sweetness values \(A_{B_j}\), and if \(A_{B_j} < K\), count it and add it to the total.

The key point here is that there is no need to search through all fruits \(1..N\) each time or perform complex matching against the blemish list.
For example, an implementation like “for each fruit \(i\), linearly search whether it is blemished” would be \(O(NM)\) in the worst case (since \(N,M \le 2\times 10^5\)), which is far too slow.

In this problem, the blemished fruit numbers \(B_j\) are given from the start, so we can simply iterate through \(B\) in order, processing in \(O(M)\).

(Example)
When \(A=[5,12,3,10],\ B=[2,3],\ K=10\):
- Fruit 2 has sweetness 12 (\(12 \ge 10\)) → not substandard
- Fruit 3 has sweetness 3 (\(3 < 10\)) → substandard
Therefore, the count is 1 and the total is 3.

Algorithm

  1. Read the sweetness array \(A\) (length \(N\)) and the blemished fruit number array \(B\) (length \(M\)) from input.
  2. Prepare variables cnt=0 (count of substandard items) and total=0 (total sweetness).
  3. For each \(b \in B\), do the following:
    • Retrieve sweetness \(a = A_{b}\) (in implementation, since it’s 1-indexed, use A[b-1]).
    • If \(a < K\), then cnt += 1, total += a.
  4. Output cnt total.

Complexity

  • Time complexity: \(O(N+M)\) (reading the array \(O(N)\) + scanning the blemish list \(O(M)\))
  • Space complexity: \(O(N+M)\) (for storing the input arrays. The additional space for processing itself is \(O(1)\))

Implementation Notes

  • \(B_j\) is a 1-based index, so to match Python’s 0-indexed arrays, use A[b-1].

  • Since \(N,M\) can be up to \(2\times 10^5\), using sys.stdin.buffer.read() in Python allows for faster input reading.

    Source Code

import sys

def main():
    data = list(map(int, sys.stdin.buffer.read().split()))
    N, M, K = data[0], data[1], data[2]
    A = data[3:3+N]
    B = data[3+N:3+N+M]

    cnt = 0
    total = 0
    for b in B:
        a = A[b-1]
        if a < K:
            cnt += 1
            total += a

    print(cnt, total)

if __name__ == "__main__":
    main()

This editorial was generated by gpt-5.2-high.

posted:
last update: