Text Editor
Time limit4sMemory limit1024 MB
Given line lengths, find the fewest arrow key presses to move the cursor from a start position to a target, where up and down keep the column clamped to each line's end.
- Level
Hard9 of 10
- Topics
- Shortest path, Greedy, Array
- Solved
- No attempts yet
Problem
Robert is competing in CEOI 2024. He has almost finished his solution to the hardest problem of the day and is pretty sure it will score 100 points. There is one small problem: he made a typo. His favorite mouse, which he has used since 2008, has finally broken and does not respond at all. He has to move the cursor to the typo with the arrow keys on his keyboard.
Robert's program has lines with lengths . Robert always ends his programs with an empty line, so . The cursor can be placed between two characters, or at the start or end of a line. Line therefore has possible cursor positions (called columns), numbered from 1 to . For example, a cursor on line 2 in column 6 sits after the fifth character of that line.
Robert wants to move the cursor from line , column to line , column . Find the minimum number of key presses needed to do so.
The horizontal arrow keys are simple. Pressing left moves the cursor to the previous column, or to the end of the previous line if the cursor is at the start of a line. Pressing right moves the cursor to the next column, or to the start of the next line if the cursor is at the end of a line. Pressing left at the very start of the file or right at the very end of the file has no effect.
The vertical arrow keys are slightly more complicated. Pressing up moves the cursor to the previous line, and pressing down moves it to the next line, without changing the column number. If that column is past the end of the new line, the cursor moves to the end of that line instead. If up or down would move the cursor to a line that does not exist, the cursor does not move.
Input
The first line contains the integer , the number of lines in Robert's solution.
The second line contains two integers and , the initial cursor position.
The third line contains two integers and , the target cursor position.
The fourth line contains space-separated integers , the length of each line.
Output
Print a single line containing one integer, the minimum number of key presses needed to move the cursor from to .
Constraints
for each such that