C - 果樹園の収穫計画 / Orchard Harvest Plan Editorial by admin Editorial for printing
Qwen3-Coder-480BOverview
This problem requires efficiently computing the total number of fruits that can be harvested within a specified time for each given interval.
Analysis
For each query, when harvesting from trees \(L\) through \(R\) for \(T\) units of time, the total harvest is: $\( (A_L + A_{L+1} + \cdots + A_R) \times T \)$ In other words, we just need to compute the sum over each interval (range sum).
If we compute the range sum using a loop each time, the worst case takes \(O(N)\) per query, resulting in \(O(QN)\) overall, which is too slow (\(N, Q \sim 2 \times 10^5\)).
Instead, by precomputing a prefix sum array, we can answer any range sum query in \(O(1)\). A prefix sum is a technique where we precompute cumulative sums from the beginning, allowing us to compute the sum over the interval \([L, R]\) as: $\( S[R] - S[L-1] \)\( (where \)S[0] = 0$).
This reduces the time per query to constant time, enabling efficient processing overall.
Algorithm
- Read the input and create the harvest amount array \(A\) for the fruit trees.
- Build the prefix sum array \(S\): $\( S[i] = A[0] + A[1] + \cdots + A[i-1] \)$
- For each query, compute the sum over the interval \([L, R]\) using the prefix sum array, then multiply it by the time \(T\) to obtain the answer.
Complexity
- Time complexity: \(O(N + Q)\)
- Space complexity: \(O(N)\)
Implementation Notes
- Allocate the prefix sum array with size \(N+1\) and set \(S[0] = 0\) to simplify boundary handling.
- Since the intervals in each query are given in 1-indexed form, adjust the indices appropriately when referencing the prefix sum array (e.g., \(S[R] - S[L-1]\)).
- To read input efficiently,
sys.stdin.readis used.
## Source Code
```python
import sys
input = sys.stdin.read
def main():
data = input().split()
N = int(data[0])
Q = int(data[1])
A = list(map(int, data[2:2+N]))
# 累積和配列を作成
S = [0] * (N + 1)
for i in range(N):
S[i+1] = S[i] + A[i]
result = []
idx = 2 + N
for _ in range(Q):
L = int(data[idx])
R = int(data[idx+1])
T = int(data[idx+2])
idx += 3
# 区間和を計算: S[R] - S[L-1]
range_sum = S[R] - S[L-1]
total = range_sum * T
result.append(str(total))
print('\n'.join(result))
if __name__ == "__main__":
main()
This editorial was generated by qwen3-coder-480b.
posted:
last update: