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

#FT0000069. Số lần đổi chỗ kề ít nhất (Minimum Adjacent Swaps)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Số lần đổi chỗ kề ít nhất (Minimum Adjacent Swaps)

Minimum Adjacent Swaps

Source: Luogu

Version: Phuoc Hung OJ Extended

Problem Statement

In a contest to select a wise person, an integer sequence is given in arbitrary order. The only permitted operation is to swap two elements at adjacent positions.

The goal is to transform the sequence into a non-decreasing one, meaning ai≤ai+1a_i\le a_{i+1} at every consecutive pair of positions after the operations. Negative and equal values may occur.

Find the minimum number of operations needed. Output only this number, not the sorted sequence.

Input

The first line contains nn, the number of elements.

The second line contains exactly nn integers a1,a2,…,ana_1,a_2,\ldots,a_n in their initial order.

Output

Print one integer: the minimum number of adjacent swaps.

Subtasks

  • Subtask 1 (20 points): 1≤n≤601\le n\le 60; −2147483648≤ai≤2147483647-2147483648\le a_i\le 2147483647 for every element.

  • Subtask 2 (30 points): 1≤n≤30001\le n\le 3000; −2147483648≤ai≤2147483647-2147483648\le a_i\le 2147483647 for every element.

  • Subtask 3 (50 points): 1≤n≤5000001\le n\le 500000; −2147483648≤ai≤2147483647-2147483648\le a_i\le 2147483647 for every element.

Examples

Input

4
2 8 0 3

Output

3

Explanation

Starting from [2,8,0,3][2,8,0,3], three swaps are sufficient:

  1. Swap 88 and 00: [2,0,8,3][2,0,8,3].
  2. Swap 22 and 00: [0,2,8,3][0,2,8,3].
  3. Swap 88 and 33: [0,2,3,8][0,2,3,8].

The result is non-decreasing. Initially there are exactly three inverted value pairs: (2,0)(2,0), (8,0)(8,0), and (8,3)(8,3). Each adjacent swap can eliminate at most one inversion, so fewer than three operations cannot suffice. Output 3.