This page is still under construction.

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

Children

Interview

Time limit1sMemory limit128 MB

Summary
Given a permutation on n cells, find the fewest adjacent swaps so every walk visits all cells.
Level

Medium5 of 10

Topics
Graph, Array
Solved
No attempts yet

Problem

On the playground a rectangle of unit width and length nn is drawn and divided into nn square cells. Each cell holds one natural number between 11 and nn, and all of the numbers are different (so together they form a permutation of 11 through nn). At the start one child stands on each cell. Every minute each child walks to the cell whose number is written on the cell it is currently standing on.

The children grow bored and start thinking about a different question. They want that, over the course of the whole game, every child eventually stands on every cell. To make this happen they may swap the numbers written on two adjacent cells (two cells that sit next to each other in the row). Redrawing the digits takes time, so they want to make as few swaps as possible. Find the minimum number of swaps needed.

Input

The first line contains one integer nn (1≤n≤1061 \le n \le 10^6), the number of square cells. The second line contains nn integers a1,a2,…,ana_1, a_2, \dots, a_n (1≤ai≤n1 \le a_i \le n), where aia_i is the number written on the ii-th cell. All values are distinct, so they form a permutation of 11 through nn.

Output

Print a single integer: the minimum number of swaps the children must make.

Hint

In the case where n=5n = 5 and the cells read 3 4 1 5 23\ 4\ 1\ 5\ 2, it is enough to swap the numbers on cells 33 and 44. After that a child starting on cell 11 moves 1→3→5→2→4→11 \to 3 \to 5 \to 2 \to 4 \to 1 and thereby visits every cell, so the minimum number of swaps is 11.

Examples1

  1. Example 1

    Input
    5
    3 4 1 5 2
    
    Expected output
    1