Cheerio Contest 1 S4 - Mystery Boxes

View as PDF

Submit solution

Points: 10 (partial)
Time limit: 1.0s
Java 2.0s
Python 2.0s
Memory limit: 512M

Author:
Problem type

There is a line of N boxes on a table, indexed from 1 to N. Each box is assigned a number ai between 1 and M such that every number from 1 to M appears at least once. In order to open a box with ai=m, you must have already opened a box with ai=m1. You do not need to open anything before opening a box with ai=1.

In addition, to get from index i to index j, you need to travel a distance of |ji|. You are initially at index 0, and all the boxes are closed. What is the minimum distance you need to travel in order to open a box with ai=M?

Constraints

For all subtasks:

  • 1aiMN
  • There is always at least one box with ai=m for all 1mM.
Points Awarded N
5 points 1N4000
10 points 1N5×105

Input Specification

The first line contains two integers N and M.

The second line contains N integers ai.

Output Specification

Output the minimum distance required. Please note that this number may not fit inside a 32-bit integer.

Sample Input

Copy
4 3
3 1 2 2

Sample Output

Copy
5

Explanation for Sample Output

Starting from index 0, we go to index 2, then to index 3 and then back to index 1. The total distance travelled is |20|+|32|+|13|=5. It can be shown that this is the minimal distance required.


Comments

There are no comments at the moment.