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
1 lộ trìnhBài tập thuộc lộ trình
Mục lục đề ⌄
Đang đọc
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 of integers. Every iteration performs the following steps, in order:
- Increase the iteration counter by one (printing
moo). - Scan from left to right, swapping adjacent elements whenever .
- Scan from right to left, again swapping adjacent elements whenever .
- 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 , the array length.
- Each of the following exactly lines contains one integer , in order .
Output
Print a single integer: the number of iterations performed, equal to the number of moo statements executed.
Subtasks
- Subtask 1 (20 points): ; for every ; duplicates are allowed.
- Subtask 2 (30 points): ; for every ; duplicates are allowed.
- Subtask 3 (50 points): ; for every ; duplicates are allowed.
Examples
Input
5
1
8
5
3
2
Output
2
Explanation
Initially .
- Iteration 1: the left-to-right pass produces ; the right-to-left pass produces . Since , the array is not yet sorted.
- Iteration 2: the forward pass produces , 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 in total.