Elevator
InterviewTime limit1sMemory limit512 MB
Given passenger arrival times and destination floors, choose when to dispatch the elevator to minimize the time it finally returns to floor 0.
- Level
Medium6 of 10
- Topics
- Dynamic programming, Greedy, Binary search, Array
- Solved
- No attempts yet
Problem
You have a very important job: you are responsible for an elevator in a new skyscraper.
There are people who will come to the underground parking garage on floor and wait for an elevator to take them to some upper floor. Formally, the -th person comes to the elevator at moment and wants to reach floor . The elevator has infinite capacity, so there is no limit on the number of people using the elevator at any moment. All are distinct. Passengers always enter the elevator while it is at floor .
The elevator uses the following algorithm: it stays open on floor until you send it to deliver passengers, then it moves to the highest floor it needs to reach (the maximum among all passengers currently in the elevator), dropping passengers off along the way, and returns to the parking garage. The elevator spends unit of time to move to the next floor (or to the previous floor). The time spent opening and closing the elevator doors and letting passengers enter and leave is negligible. At moment , the elevator is at floor .
You want to minimize the moment of time when the elevator will return to floor after delivering everyone.
Input
The input contains one or more test cases.
The first line of each test case contains one integer : the number of passengers ().
Each of the following lines contains two space-separated integers and : the moment of time when the -th passenger comes to the elevator, and the destination floor of the -th passenger ().
All in one test case are distinct, and passengers appear in the input in ascending order of .
The sum of the values of over all test cases does not exceed . The test cases just follow one another without any special separators.
Output
For each test case, print one integer: the minimum possible moment of time when the elevator will return after delivering all passengers.