This page is still under construction.

Parts of this page are still being built. What you see may change.

Rope Mail

Time limit2sMemory limit256 MB

Summary
Given n people on a line where person i sends a message to a[i], find the minimum total distance the rope must travel so every envelope reaches its recipient.
Level

Medium7 of 10

Topics
Dynamic programming, Intervals, Implementation, Math
Solved
No attempts yet

Problem

We are used to various means of communication. A phone, email, or a social network always helps us pass some information to another person, who may be on the other side of the Earth. At a well-known company that provides email and instant messaging services, a candidate who wants to work there is given the following test task: compute the minimum time needed to deliver all messages to their recipients using a system called "Rope Mail".

The system works as follows. On a single line along which a rope is stretched, there are n people, numbered in order from 1 to n. Between people whose numbers differ by 1 there is nobody else, and the distance between all such neighbors is the same and equals 1 meter.

Each of them wants to send a message to one of the other participants. Person i wants to send a message to person ai. Each person attaches an envelope with their message to the rope near themselves and writes the recipient's number on it. Then the rope moves several times along the line in different directions, and as soon as an envelope addressed to a person appears in front of them, they take it and receive the message.

Since the rope moves at a constant speed, the time needed to deliver all messages to their recipients depends on the total distance the rope moves. The task given to the interview candidate is to minimize this distance.

For example, suppose the first person wants to send a message to the second, the second to the third, the third to the second, and the fourth to the first. Then the rope must be moved forward by 1 meter, after which the second person receives the message from the first, and the third receives the message from the second. After that the rope must be moved back by 2 meters (after which the second person receives the message from the third) and by another 2 meters (the first person receives the message from the fourth). In total, the rope must be moved 5 meters.

Input

The first line of the input contains a single integer n (2 ≤ n ≤ 1000), the number of people exchanging messages. The second line contains n integers ai (1 ≤ ai ≤ n, ai ≠ i), the number of the person to whom the message of participant i is addressed.

Output

Print a single integer: the minimum total distance the rope must be moved so that all messages reach their destinations.

Examples1

  1. Example 1

    Input
    4
    2 3 2 1
    
    Expected output
    5