Official

C - 果樹園の収穫計画 / Orchard Harvest Plan Editorial by admin Editorial for printing

GPT 5.2 High

Overview

For each query \((L, R, T)\), the problem asks us to quickly compute the total harvesting speed over the interval \([L, R]\) multiplied by \(T\). By using prefix sums (precomputation), we can process each query in \(O(1)\).

Analysis

Tree \(i\) can harvest \(A_i\) fruits per hour, so if we harvest from all trees in the interval \([L, R]\) simultaneously, the total per hour is \([ A_L + A_{L+1} + \cdots + A_R ]\) Since we continue this for \(T\) hours, the answer is \([ (A_L + \cdots + A_R)\times T ]\)

Why the naive approach is too slow

If we sum \(A_L\) through \(A_R\) for each query, it takes up to \(O(N)\) per query.
With \(Q\) queries, the worst case is \(O(NQ)\), which is far too slow for the maximum constraints of \(N=Q=2\times 10^5\).

Solution (key insight)

Since we need to compute “range sums” repeatedly, we can precompute a prefix sum array to retrieve any range sum instantly.
Specifically, define the prefix sum array \(pref\) as: - \(pref[0]=0\) - \(pref[i]=A_1+\cdots+A_i\)

Then the range sum is: \([ A_L+\cdots+A_R = pref[R]-pref[L-1] ]\)

Concrete example

For \(A=[3,1,4,1,5]\),
\(pref=[0,3,4,8,9,14]\).
For example, if \((L,R,T)=(2,4,10)\), the range sum is \(pref[4]-pref[1]=9-3=6\), and the answer is \(6\times 10=60\).

Algorithm

  1. Build the prefix sum array \(pref\) (length \(N+1\)) from the array \(A\) of length \(N\).
    • \(pref[0]=0\)
    • \(pref[i]=pref[i-1]+A_i\)
  2. For each query \((L,R,T)\):
    • Compute the range sum \(S = pref[R]-pref[L-1]\)
    • Output the answer \(S\times T\)

Complexity

  • Time complexity: Precomputation \(O(N)\), each query \(O(1)\), so the total is \(O(N+Q)\)
  • Space complexity: \(O(N)\) for the prefix sum array

Implementation tips

  • The trick is to create \(pref\) with length \(N+1\) so that even when \(L\) is 1, we can use \(pref[L-1]=pref[0]\).

  • Since the input size is large, reading all input at once with sys.stdin.buffer.read() is faster.

  • The answer can be as large as \((\sum A_i)\times T\), so depending on the language, 64-bit integers may be required (Python handles this automatically).

    Source Code

import sys

def main():
    data = list(map(int, sys.stdin.buffer.read().split()))
    it = iter(data)
    N = next(it)
    Q = next(it)

    pref = [0] * (N + 1)
    for i in range(1, N + 1):
        pref[i] = pref[i - 1] + next(it)

    out_lines = []
    for _ in range(Q):
        L = next(it)
        R = next(it)
        T = next(it)
        out_lines.append(str((pref[R] - pref[L - 1]) * T))

    sys.stdout.write("\n".join(out_lines))

if __name__ == "__main__":
    main()

This editorial was generated by gpt-5.2-high.

posted:
last update: