Under construction

Still being built. Things may change

Roller Coaster Railroad

Time limit2sMemory limit512 MB

Summary
Order n railroad sections so each entry speed stays within its limit, then find the minimum total length of track placed between them.
Level

Hard9 of 10

Topics
Sorting, Dynamic programming, Greedy
Solved
No attempts yet

Problem

Anna works at an amusement park and is in charge of building the railroad for a new roller coaster. She has already designed nn special sections, numbered from 0 to n−1n - 1, that affect the speed of the roller coaster train. She now has to join them into a final design of the roller coaster. For this problem, the length of the train is zero.

For each ii with 0≤i≤n−10 \le i \le n - 1, special section ii has two properties:

  1. When entering the section, there is a speed limit: the speed of the train must be less than or equal to sis_i km/h.
  2. When leaving the section, the speed of the train is exactly tit_i km/h, regardless of the speed at which the train entered the section.

The finished roller coaster is a single railroad line that contains the nn special sections in some order. Each of the nn sections must be used exactly once. Consecutive sections are connected with tracks. Anna chooses the order of the nn sections, then decides the lengths of the tracks. A track length is measured in meters and may be any non-negative integer, including zero. Each meter of track between two special sections slows the train down by 1 km/h. At the start of the ride, the train enters the first special section in the chosen order at 1 km/h.

The final design must satisfy the following:

  • The train does not violate any speed limit when entering a special section.
  • The speed of the train is positive at all times.

In all subtasks except subtask 3, find the minimum possible total length of track between sections. In subtask 3, only check whether a valid design exists in which every track has zero length.

Constraints

In all subtasks, 1≤si≤1091 \le s_i \le 10^9 and 1≤ti≤1091 \le t_i \le 10^9.

Examples1

  1. Example 1

    Input
    1
    5 3
    
    Expected output
    0