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

#FT0000203. Số vòng sắp xếp hai chiều (Out of Sorts)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Số vòng sắp xếp hai chiều (Out of Sorts)

Out of Sorts

Source: USACO

Version: Phuoc Hung OJ Extended

Problem Statement

Bessie is experimenting with a bidirectional variant of bubble sort on an array AA of nn integers. Every iteration performs the following steps, in order:

  1. Increase the iteration counter by one (printing moo).
  2. Scan i=1,2,…,n−1i=1,2,\ldots,n-1 from left to right, swapping adjacent elements whenever Ai+1<AiA_{i+1}<A_i.
  3. Scan i=n−1,n−2,…,1i=n-1,n-2,\ldots,1 from right to left, again swapping adjacent elements whenever Ai+1<AiA_{i+1}<A_i.
  4. Check every adjacent pair. If the array is nondecreasing, stop; otherwise repeat.

Even if the array is initially sorted, the algorithm executes at least one iteration. Equal elements are never swapped merely because they are equal.

Determine the number of times moo is printed before the algorithm terminates.

Input

  • The first line contains the integer nn, the array length.
  • Each of the following exactly nn lines contains one integer AiA_i, in order i=1,2,…,ni=1,2,\ldots,n.

Output

Print a single integer: the number of iterations performed, equal to the number of moo statements executed.

Subtasks

  • Subtask 1 (20 points): 1≤n≤101\le n\le10; 0≤Ai≤1090\le A_i\le10^9 for every 1≤i≤n1\le i\le n; duplicates are allowed.
  • Subtask 2 (30 points): 1≤n≤20001\le n\le2000; 0≤Ai≤1090\le A_i\le10^9 for every 1≤i≤n1\le i\le n; duplicates are allowed.
  • Subtask 3 (50 points): 1≤n≤1051\le n\le10^5; 0≤Ai≤1090\le A_i\le10^9 for every 1≤i≤n1\le i\le n; duplicates are allowed.

Examples

Input

5
1
8
5
3
2

Output

2

Explanation

Initially A=[1,8,5,3,2]A=[1,8,5,3,2].

  • Iteration 1: the left-to-right pass produces [1,5,3,2,8][1,5,3,2,8]; the right-to-left pass produces [1,2,5,3,8][1,2,5,3,8]. Since 5>35>3, the array is not yet sorted.
  • Iteration 2: the forward pass produces [1,2,3,5,8][1,2,3,5,8], and the backward pass makes no changes. The array is now nondecreasing, so the algorithm stops.

The moo statement runs once at the beginning of each iteration, giving 22 in total.