Yet Another Contest 8 P1 - Permutation Sorting

View as PDF

Submit solution


Points: 5 (partial)
Time limit: 3.0s
Memory limit: 256M

Author:
Problem type

Nils likes sorted permutations. He currently has a permutation of the first N positive integers p1,p2,,pN, and wishes to sort it. He can apply the following operation any number of times:

  • Choose integers l,r satisfying 1lrN. Then, sort the subarray pl,pl+1,,pr, leaving the other elements unchanged. The cost of the operation is rl+1.

For example, if the permutation was 1,5,3,4,2, and Nils chooses l=2 and r=4, then the permutation will become 1,3,4,5,2, incurring a cost of 3.

What is the minimum total cost to sort the permutation?

Constraints

1N106

p1,p2,,pN is a permutation of the integers 1,2,,N, that is, every integer between 1 and N (inclusive) occurs exactly once in p.

Subtask 1 [20%]

There exists an optimal solution which applies at most one operation.

Subtask 2 [20%]

1N2000

Subtask 3 [60%]

No additional constraints.

Input Specification

The first line contains a single integer, N.

The second line contains N space-separated integers, p1,p2,,pN.

Output Specification

On a single line, output the minimum total cost to sort Nils' permutation.

Sample Input

Copy
6
2 1 3 6 5 4

Sample Output

Copy
5

Explanation

It is optimal to first sort the subarray with l=1 and r=2. Then, the subarray with l=4 and r=6 can be sorted.


Comments

There are no comments at the moment.