PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#FT0000198. Chi phí nhỏ nhất để sắp xếp (Minimum Cost Sort)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Chi phí nhỏ nhất để sắp xếp (Minimum Cost Sort)

Minimum Cost Sort

Source: AtCoder

Version: Phuoc Hung OJ Extended

Problem Statement

You are given a permutation P=(P1,P2,…,PN)P=(P_1,P_2,\ldots,P_N) containing each integer from 11 to NN exactly once.

You may perform the following operation any number of times, including zero: choose an index ii with 1≤i<N1\le i<N, pay a cost of ii, and swap the adjacent elements PiP_i and Pi+1P_{i+1}. The cost depends on the swap position, not on the values being swapped.

Find the minimum total cost required to obtain the increasing permutation 1,2,…,N1,2,\ldots,N.

Input

  • The first line contains an integer NN, the length of the permutation.
  • The second line contains exactly NN integers P1,P2,…,PNP_1,P_2,\ldots,P_N, in their original order.

Output

Print one integer: the minimum total cost of adjacent swaps needed to sort the permutation. If it is already sorted, print 0.

Subtasks

  • Subtask 1 (20 points): 2≤N≤92\le N\le9; PP is a permutation of 1,2,…,N1,2,\ldots,N.
  • Subtask 2 (30 points): 2≤N≤20002\le N\le2000; PP is a permutation of 1,2,…,N1,2,\ldots,N.
  • Subtask 3 (50 points): 2≤N≤2⋅1052\le N\le2\cdot10^5; PP is a permutation of 1,2,…,N1,2,\ldots,N.

Examples

Input

3
3 2 1

Output

4

Explanation

Initially P=[3,2,1]P=[3,2,1]. One way to sort it is:

  1. Swap at i=1i=1 for cost 11: [3,2,1]→[2,3,1][3,2,1]\to[2,3,1].
  2. Swap at i=2i=2 for cost 22: [2,3,1]→[2,1,3][2,3,1]\to[2,1,3].
  3. Swap at i=1i=1 for cost 11: [2,1,3]→[1,2,3][2,1,3]\to[1,2,3].

The total cost is 1+2+1=41+2+1=4. The initial permutation has three inversions, so at least three adjacent swaps are necessary; this sequence achieves the minimum possible total cost for the example. Thus the answer is 4.