PDP-25 (2013) - Camp senior - 2 (gymnast)

View as PDF

Submit solution

Points: 30 (partial)
Time limit: 2.0s
Memory limit: 64M

Author:
Problem types
Allowed languages
C, C++, Java, Pascal, Python

Problem

A gym teacher asks his students to line up in descending order of height. However, they line up randomly, and the teacher must arrange them in order by himself. Each time, the teacher chooses a student and moves them from position i to position j. If i > j, then the positions of the students between i and j - 1 increase by 1. Conversely, if i < j, then the positions of the students between i + 1 and j decrease by 1. The teacher continues to make these moves until each student is in the correct position. Each time the teacher makes a move of a student from position i to position j, the teacher is forced to take i + j steps.

Write a program to find the minimum total number of steps the teacher must take to place all the students in the correct order.

Input

The input will consist of two lines. The first line will contain a natural number N, the number of students. The second line will contain N integers x_1, x_2, ... x_N, separated in pairs by a single space: the heights of the students initially at positions 1, 2, ... N, respectively. Assume that there are no two students with the same height.

Output

The output must consist of a single line containing only one natural number: the minimum total number of steps the teacher must take.

Constraints

2 \le N \le 1.000
1 \le x_i \le 1.000.000
Execution time limit: 2 sec.
Memory limit: 64 MB.

Examples of Input - Output
1st

STDIN (gymnast.in)

5
20 30 5 15 10

STDOUT (gymnast.out)

11

Explanation of the first example: The teacher can move student 30 from position 2 to position 1 (cost 3) and then move student 5 from position 3 to position 5 (cost 8). Total cost is 3 + 8 = 11. This cost is also the minimum possible.


2nd

STDIN (gymnast.in)

10
9 6 2 10 8 7 4 5 1 3

STDOUT (gymnast.out)

52

Comments

There are no comments at the moment.