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

#FT0000196. Bốn phương pháp sắp xếp (Sorting Methods)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Bốn phương pháp sắp xếp (Sorting Methods)

Sorting Methods

Source: CSES

Version: Phuoc Hung OJ Extended

Problem Statement

Given a permutation pp of the integers from 11 to nn, transform it into 1,2,…,n1,2,\ldots,n.

Consider four independent methods, each permitting repeated operations:

  1. Swap two adjacent elements.
  2. Swap any two elements.
  3. Remove one element and insert it at any position, preserving the relative order of all remaining elements.
  4. Remove one element and insert it at the front, preserving the relative order of all remaining elements.

For each method, determine its minimum number of operations. Every method starts with the original permutation, independently of all others.

Input

  • The first line contains an integer nn, the permutation length.
  • The second line contains nn integers p1,p2,…,pnp_1,p_2,\ldots,p_n, each integer from 11 to nn appearing exactly once.

Output

Print one line containing four integers, in the order of methods 11, 22, 33, 44. Each is the minimum number of operations for that method.

Subtasks

  • Subtask 1 (20 points): 1≤n≤81\le n\le 8; pp is a permutation of 1,2,…,n1,2,\ldots,n.

  • Subtask 2 (30 points): 1≤n≤20001\le n\le 2000; pp is a permutation of 1,2,…,n1,2,\ldots,n.

  • Subtask 3 (50 points): 1≤n≤2⋅1051\le n\le 2\cdot10^5; pp is a permutation of 1,2,…,n1,2,\ldots,n.

Examples

Input

8
7 8 2 6 5 1 3 4

Output

20 6 5 6

Explanation

Initially p=[7,8,2,6,5,1,3,4]p=[7,8,2,6,5,1,3,4]. There are 2020 inversions, giving 2020 adjacent swaps. The cycle decomposition has one cycle of length 77 and the fixed element 55, so arbitrary swaps require 66 operations. An increasing subsequence of length 33, such as [2,3,4][2,3,4], can be left in place relative to the other retained elements; therefore 8−3=58-3=5 moves are required. Finally, the target suffix [7,8][7,8] already appears in order, so moving 6,5,4,3,2,16,5,4,3,2,1 successively to the front sorts the permutation in 66 moves. A longer retained target suffix is impossible.