SystemYou are a competitive-programming assistant. Deliver correct, complete, runnable solutions that read standard input and write standard output. Give only a concise rationale: approach, correctness idea, and time/space com...
You are a competitive-programming assistant. Deliver correct, complete, runnable solutions that read standard input and write standard output. Give only a concise rationale: approach, correctness idea, and time/space complexity.
User2026-11-08T22:20:03.537Z
Two-Stage Bakery
Topic: Sorting and greedy | Difficulty: hard
Problem
A bakery processes n batches. Every batch must first be kneaded by the single kneading machine for a_i minutes and afterwards baked by the single oven for b_i minutes. Each machine handles one batch at a time and cannot be interrupted; a batch can enter the oven only after its kneading is complete, and the oven may wait idle. Both machines process the batches in the same chosen order. Print the smallest possible time at which the last batch leaves the oven (all work starts at time 0).
Input
The first line contains n. Each of the next n lines contains a_i and b_i.
Output
Print one integer: the minimum finishing time.
Constraints
1 <= n <= 2*10^5
1 <= a_i, b_i <= 10^9
Examples
Example 1
Input:
markdown
33 65 21 2
Output:
markdown
12
Note: Order (1,2), (3,6), (5,2): kneading ends at 1, 4, 9; the oven finishes at 3, 10, 12.
Example 2
Input:
markdown
14 5
Output:
markdown
9
Solve this in Ruby, Java 17, JavaScript (Node.js), one complete program per language. Include a concise rationale (approach, correctness idea, time/space complexity).
Assistant2026-11-08T22:20:05.511Z
Approach. Apply Johnson's rule: batches with a_i <= b_i go first in increasing a_i, the rest go afterwards in decreasing b_i. Simulate the two machines to get the finishing time.
Correctness. For two adjacent batches i, j, putting i first is no worse whenever min(a_i, b_j) <= min(a_j, b_i); this relation is realised by the described order, and exchanges toward it never increase the makespan.
Complexity. Time: O(n log n). Space: O(n).
Ruby
ruby
n = gets.to_i
g1 = []
g2 = []
n.times do
a, b = gets.split.map(&:to_i)
if a <= b
g1 << [a, b]
else
g2 << [a, b]
endend
g1.sort_by! { |x| x[0] }
g2.sort_by! { |x| -x[1] }
t1 = 0
t2 = 0
(g1 + g2).each do |a, b|
t1 += a
t2 = [t1, t2].max + b
end
puts t2