# Metro Delivery — Solution ## Comparing solutions The problem setter’s method uses a heap to select the road segment with maximum current marginal gain and a segment tree to maintain waiting slack. It compresses in one batch until the next event: the budget is exhausted, a segment reaches zero, or a station's waiting slack reaches zero. The last event truncates the affected interval and updates candidates. Recomputing only at such events avoids one operation per budget unit. The marginal-gain and event-count proofs below retain this reasoning. A station with zero resources need not wait for its supplied time; use the corresponding effective threshold. The implementation must also handle one station, zero budget and large cumulative times. Codex (GPT-6) contributed these implementation details and boundary explanations. The heap, segment tree and event-batching algorithm takes $O(n\log(n+1))$ time and $O(n)$ space. ## Arrival times and the objective The train cannot return. If $\mathrm{Num}_i>0$ , it must collect the resources at station $i$ , so it cannot leave before $T_i$ . If $\mathrm{Num}_i=0$ , there is nothing to collect there, and its production time imposes no departure constraint. Define the effective release time $R_i=T_i$ for a positive quantity and $R_i=0$ for a zero quantity; also set $R_n=0$ . Fix the reduced travel times $D_i$ . Extra waiting can only delay deliveries, so optimal arrival times satisfy $$A_1=0,\qquad A_{i+1}=\max(A_i,R_i)+D_i$$ Station $j$ receives $W_j=\sum_{i