C - 工場見学ツアー / Factory Tour Editorial by admin
Qwen3-Coder-480BOverview
By preprocessing the time required for each interval, we can efficiently compute the tour completion time for each group.
Analysis
Each group must visit all areas within the specified interval \([L_j, R_j]\), and the total time required is
$\(
T_{L_j} + T_{L_j+1} + \cdots + T_{R_j}
\)\(
If we compute this naively each time, it takes \)O(N)\( in the worst case, resulting in \)O(MN)$ overall, which will TLE due to the large constraints.
Therefore, we consider using prefix sums to compute interval sums in \(O(1)\).
Define the prefix sum array \(prefix\_sum\) as follows:
$\(
prefix\_sum[i] = T_1 + T_2 + \cdots + T_i
\)\(
Then, the sum over the interval \)[L, R]\( can be computed as:
\)\(
\text{sum}(L, R) = prefix\_sum[R] - prefix\_sum[L - 1]
\)\(
This allows us to compute the interval sum for each query in \)O(1)\(, resulting in \)O(N + M)$ overall.
Algorithm
- Read the visit time \(T_i\) for each area and construct the prefix sum array \(prefix\_sum\).
- For each group, compute the total time for the interval \([L_j, R_j]\) from the prefix sum array, in addition to the arrival time \(S_j\).
- The tour completion time for each group is the arrival time plus the total time.
Complexity
- Time complexity: \(O(N + M)\)
- Space complexity: \(O(N)\)
Implementation Notes
When computing the prefix sum, prepending a 0 at the beginning eliminates the need for special-case handling when \(prefix\_sum[L - 1]\) would otherwise not exist.
Using a method that reads all input at once and splits it (
sys.stdin.read) enables faster input processing.Source Code
import sys
from itertools import accumulate
def main():
input = sys.stdin.read
data = input().split()
N = int(data[0])
M = int(data[1])
T = list(map(int, data[2:2+N]))
# 累積和を計算 (1-indexed)
prefix_sum = [0] + list(accumulate(T))
idx = 2 + N
results = []
for _ in range(M):
S = int(data[idx])
L = int(data[idx+1])
R = int(data[idx+2])
idx += 3
# 区間 [L, R] の合計時間 = prefix_sum[R] - prefix_sum[L-1]
total_time = prefix_sum[R] - prefix_sum[L-1]
finish_time = S + total_time
results.append(finish_time)
print('\n'.join(map(str, results)))
if __name__ == "__main__":
main()
This editorial was generated by qwen3-coder-480b.
posted:
last update: