Zenyk and the Martian permutation
Limits: 2 sec., 256 MiB
This statement was translated automatically from Ukrainian.
Zenyk received a Martian permutation \(p\) of numbers from 1 to \(n\) as a gift from Ilona.
A number \(k\) is called good if Zenyk can sort the given permutation by performing the following operation any number of times: choose \(i\) and swap \(p_i\) and \(p_{i + k}\).
Help Zenyk determine all positive integers that are good.
Input
The first line contains an integer \(n\) — the size of the permutation.
The second line contains \(n\) integers \(p_i\) — the permutation.
Output
In the first line, print an integer \(m\) — the number of good numbers.
In the second line, print \(m\) integers — the good numbers in ascending order.
Constraints
\(2 \le n \le 10^5\),
\(1 \le p_i \le n\),
there exists an index \(i\) such that \(p_i \neq i\),
for 60% of the tests, an additional constraint holds: \(n \le 2000\).
Samples
| Input (stdin) | Output (stdout) |
|---|---|
| 3 3 2 1 | 2 1 2 |
| Input (stdin) | Output (stdout) |
|---|---|
| 7 7 5 3 6 2 4 1 | 1 1 |
Submit a solution
| Element Type | Created | Who | Problem | Compiler | Result | Time (sec.) | Memory (MiB) | # | Actions |
|---|
Зеник і марсіанська перестановка - Розбір
Операція з числом \(k\) переставляє елементи лише між позиціями, що дають однакову остачу при діленні на \(k\). Число \(p_i\) має потрапити з позиції \(i\) на позицію \(p_i\), тож \(k\) має ділити \(|p_i - i|\) для кожного \(i\). І навпаки, якщо це так, то кожне число вже стоїть у «своєму» класі остач, а всередині класу обміни сусідніх (через \(k\)) позицій дозволяють отримати будь-яку перестановку, як у сортуванні бульбашкою.
Отже, \(k\) добре тоді й лише тоді, коли воно ділить \(d = \gcd_i |p_i - i|\). За умовою \(d > 0\), і \(d \le n - 1\), тож усі дільники \(d\) є допустимими кроками. Знаходимо \(d\), перебираємо його дільники до \(\sqrt{d}\) і виводимо їх у порядку зростання. Складність — \(O(n \log n + \sqrt{n})\).
| Element Type | Created | Who | Problem | Compiler | Result | Time (sec.) | Memory (MiB) | # | Actions |
|---|