#P5181. Mirko's Shuffler
Mirko's Shuffler
Mirko's Shuffler
Mirko invented a device known as the "Shuffler". The machine operates on an infinite tape that has N columns (numbered 1 through N) and infinitely many rows. Initially, only the first row of the tape is filled: column i contains the integer i for i = 1,2,…,N, and every row below is blank.
Mirko also provides a permutation s = (s1, s2, …, sN) of length N. The machine has a row pointer starting at the first row. Every time the machine runs, it takes the current row (pointed by the row pointer) and for each column i, moves the integer located in column i of the current row to column si of the next row. After processing all N columns, the row pointer advances one row.
This process is repeated an infinite number of times. After that, Mirko cuts off the first C columns and the last D columns of the tape, forming a new tape. In the new tape, the columns correspond to positions C+1 through N-D of the original tape.
Your task is: Given integers N, A, B, C, D and the permutation s, determine how many rows among rows A through B of the new tape are identical to the first row of the new tape.
A row in the tape is a vector of numbers. The first row of the new tape is simply the subvector of the original first row from column C+1 to column N-D. For any subsequent row, its content is obtained by applying the permutation repeatedly. In other words, if the permutation is denoted by \(P\), then the r-th row is the result of applying \(P^{r-1}\) (the permutation applied \(r-1\) times) to the initial row. A row \(r\) is identical to the first row of the new tape if and only if for every column index j with C+1 \le j \le N-D, we have
\(P^{r-1}(j) = j\).
This condition is equivalent to requiring that for every cycle of the permutation \(P\) that intersects the set of indices \(\{C+1, C+2, \ldots, N-D\}\), the cycle length \(L\) divides \(r-1\). Let \(T\) be the least common multiple (\(\mathrm{lcm}\)) of all such cycle lengths. Then a row \(r\) (with \(A \le r \le B\)) matches the first row if and only if \((r-1) \equiv 0 \; (\bmod\; T)\).
Note: If the new tape is empty (i.e. if \(C + D \ge N\)), then we consider every row to be identical to the first row of the new tape.
inputFormat
The input consists of two lines. The first line contains five integers: N A B C D
(
N is the number of columns, A and B specify the range of rows to be examined, and C and D indicate the number of columns removed from the beginning and end, respectively).
The second line contains N space‐separated integers representing the permutation s (s1 s2 ... sN
).
outputFormat
Output a single integer representing the number of rows between rows A and B (inclusive) of the new tape that are identical to the first row of the new tape.
sample
5 1 10 1 1
3 4 5 1 2
2