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

#FT0000234. Số vòng sắp xếp nổi bọt I (Bubble Sort Rounds I)

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 nổi bọt I (Bubble Sort Rounds I)

Bubble Sort Rounds I

Source: CSES

Version: Phuoc Hung OJ Extended

Problem Statement

An array of nn integers is sorted by bubble sort. In one round, the algorithm scans adjacent pairs from left to right, examining positions i=1,2,…,n−1i=1,2,\ldots,n-1 in order. If the element currently at position ii is greater than the element at position i+1i+1, the two elements are swapped immediately. Equal elements are not swapped. Each later comparison uses the array as modified by preceding swaps in the same round.

Determine the minimum number of rounds needed to make the array nondecreasing. The answer is 00 if the array is already sorted. Do not count an extra no-swap verification round after the array is sorted.

Input

  • The first line contains the integer nn, the array length.
  • The second line contains exactly nn integers x1,x2,…,xnx_1,x_2,\ldots,x_n from left to right.

Output

Print one integer: the required number of bubble sort rounds.

Subtasks

  • Subtask 1 (20 points): 1≤n≤501\le n\le 50; 1≤xi≤10000000001\le x_i\le 1000000000 for every 1≤i≤n1\le i\le n.
  • Subtask 2 (30 points): 1≤n≤30001\le n\le 3000; 1≤xi≤10000000001\le x_i\le 1000000000 for every 1≤i≤n1\le i\le n.
  • Subtask 3 (50 points): 1≤n≤2000001\le n\le 200000; 1≤xi≤10000000001\le x_i\le 1000000000 for every 1≤i≤n1\le i\le n.

Examples

Input

5
3 2 4 1 4

Output

3

Explanation

Initially the array is [3,2,4,1,4][3,2,4,1,4]. Each round compares adjacent pairs from left to right, using the result of each swap immediately.

  • After round 11: [2,3,1,4,4][2,3,1,4,4]. The pairs 3,23,2 and then 4,14,1 are swapped.
  • After round 22: [2,1,3,4,4][2,1,3,4,4]. The value 11 moves one more position to the left.
  • After round 33: [1,2,3,4,4][1,2,3,4,4]. The array is now nondecreasing.

The array was still unsorted after round 22 because its first two elements were [2,1][2,1]. Hence the answer is 33.