Segments

Time limit1sMemory limit128 MB

Summary
On each row of an n by n grid you must walk the whole interval [L(i), R(i)], moving only left, right, or down; find the shortest path from (1,1) to (n,n).
Level

Medium7 of 10

Topics
Dynamic programming, Greedy, Implementation
Solved
No attempts yet

Problem

You start at the top-left cell (1,1)(1, 1) of an n×nn \times n grid whose rows and columns are numbered 11 through nn (1≤n≤200001 \le n \le 20000). For each row ii you are given two integers L(i)L(i) and R(i)R(i) with 1≤L(i)≤R(i)≤n1 \le L(i) \le R(i) \le n, describing a horizontal segment on that row.

Your path must, on every row ii, visit all cells of that row's segment:

(i,L(i)), (i,L(i)+1), …, (i,R(i)).(i, L(i)),\ (i, L(i)+1),\ \dots,\ (i, R(i)).

You may only move left, right, or down; you can never move up. Moving to an adjacent cell in the same row costs one step, and dropping straight down from row ii to row i+1i+1 also costs one step. Because you can never move up, the rows must be covered in the order 1,2,…,n1, 2, \dots, n.

After covering the segment on the last row nn, move to the bottom-right cell (n,n)(n, n) if you are not already there. Report the total number of steps of the shortest path from (1,1)(1, 1) to (n,n)(n, n) that covers every segment.

Input

The first line contains the integer nn, the number of rows and columns of the grid. Each of the next nn lines contains two integers L(i)L(i) and R(i)R(i) (1≤L(i)≤R(i)≤n1 \le L(i) \le R(i) \le n), the endpoints of the segment on row ii.

Output

Print a single integer: the length (number of steps) of the shortest path from (1,1)(1, 1) to (n,n)(n, n) that covers every segment [L(i),R(i)][L(i), R(i)].

Examples1

  1. Example 1

    Input
    6
    2 6
    3 4
    1 3
    1 2
    3 6
    4 5
    
    Expected output
    24