Sorting
Time limit0.3sMemory limit64 MB
Given a permutation, find all gap sizes X for which repeatedly scanning and swapping positions i and i+X until a pass makes no swap leaves the array sorted.
- Level
Medium7 of 10
- Topics
- Sorting, Array, Math, Implementation
- Solved
- No attempts yet
Problem
Little P has just learned the shell sort algorithm. He wrote code that is meant to sort an array of integers into ascending order. Let be the array to be sorted.
gap = X;
do
{ ok = 1;
for (i = 1; i<= N - gap; i++)
if (A[i] > A[i+gap])
{ temp = A[i];
A[i] = A[i+gap];
A[i+gap] = temp;
ok = 0;
}
if (gap/2 > 1) gap=gap/2; else gap=1;
} while (ok == 0);
Here i, N, X, gap, temp, and ok are integers (the int type in C/C++).
While typing the code, Little P forgot to copy line 11 (the line if (gap/2 > 1) gap=gap/2; else gap=1;). Because that line is missing, gap is never reduced: it keeps its initial value X for the whole run, so the loop just repeats the same fixed-gap pass over and over until an entire pass makes no swaps.
You are given the array . It has distinct elements, each between and .
Find every value of for which this algorithm (with line 11 missing) still sorts correctly. We call such values of valid.
Input
The first line contains one integer .
The second line contains integers separated by single spaces, describing the array .
Output
On the first line, print the number of valid values of .
On the second line, print all valid values of in ascending order, separated by single spaces.
Constraints
- is a permutation of (all elements are distinct).
Hint
For example, take and . The valid values of are:
- : swaps happen at the position pairs .
- : swaps happen at the position pairs .