Segments
Time limit1sMemory limit128 MB
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 of an grid whose rows and columns are numbered through (). For each row you are given two integers and with , describing a horizontal segment on that row.
Your path must, on every row , visit all cells of that row's segment:
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 to row also costs one step. Because you can never move up, the rows must be covered in the order .
After covering the segment on the last row , move to the bottom-right cell if you are not already there. Report the total number of steps of the shortest path from to that covers every segment.
Input
The first line contains the integer , the number of rows and columns of the grid. Each of the next lines contains two integers and (), the endpoints of the segment on row .
Output
Print a single integer: the length (number of steps) of the shortest path from to that covers every segment .