eolymp
bolt
Try our new interface for solving problems
Problems

Roller Coaster Railroad

Roller Coaster Railroad

Anna is working in an amusement park and she is in charge of building the railroad for a new roller coaster. She has already designed **n** special sections (conveniently numbered from $0$ to $n - 1$ that affect the speed of a roller coaster train. She now has to put them together and propose a final design of the roller coaster. For the purpose of this problem you may assume that the length of the train is zero. For each $i$ between $0$ and $n - 1$, inclusive, the special section has two properties: \begin{itemize} \item when entering the section, there is a speed limit: the speed of the train must be less or equal to $s_i$ km/h (kilometers per hour), \item when leaving the section, the speed of the train is exactly $t_i$ km/h, regardless of the speed at which the train entered the section. \end{itemize} The finished roller coaster is a single railroad line that contains the $n$ special sections in some order. Each of the $n$ sections should be used exactly once. Consecutive sections are connected with tracks. Anna should choose the order of the $n$ sections and then decide the lengths of the tracks. The length of a track is measured in meters and may be equal to any non-negative integer (possibly zero). Each meter of the track between two special sections slows the train down by $1$ km/h. At the beginning of the ride, the train enters the first special section in the order selected by Anna, going at $1$ km/h. The final design must satisfy the following requirements: \begin{itemize} \item the train does not violate any speed limit when entering the special sections; \item the speed of the train is positive at any moment. \end{itemize} Your task is to find the minimum possible total length of tracks between sections. \InputFile First line contains number $n~(2 \le n \le 2 \cdot 10^5)$. Each of the next $n$ lines contains numbers $s_i$ and $t_i~(1 \le i \le n, 1 \le s_i, t_i \le 10^9)$. \OutputFile Print the minimum possible total length of all tracks between sections.
Time limit 1 second
Memory limit 128 MiB
Input example #1
4
1 7
4 3
5 8
6 6
Output example #1
3
Input example #2
2
753393670 164885444
893746473 737884286
Output example #2
0
Source 2016 IOI Kazan, Russia, Day 1