Powers of permutations

Given an nn, a permutation of {0,1,…n−1}\{0, 1, \ldots n-1\} is a sequence where each of the numbers 0,1,…n−10, 1, \ldots n-1 occurs exactly once. For example, if n=3n = 3, the sequences (120)(1\ 2\ 0), (201)(2\ 0\ 1) and (012)(0\ 1\ 2) are permutations of {0,1,2}\{0, 1, 2\}.

Given two permutations σ=(σ0,…,σn−1)\sigma = (\sigma_{0}, \ldots, \sigma_{n-1}) and τ=(τ0,…,τn−1)\tau = (\tau_{0}, \ldots, \tau_{n-1}) of {0\{0, 11, …n−1\ldots n-1 }\}, their product σ∘τ\sigma \circ \tau is defined as the permutation ρ=(ρ0,…,ρn−1)\rho = (\rho_{0}, \ldots, \rho_{n-1}) such that ρi=στi\rho_{i} = \sigma_{\tau_{i}}. For example, if n=3n = 3, σ=(120)\sigma = (1\ 2\ 0) and τ=(201)\tau = (2\ 0\ 1), then σ∘τ=(012)\sigma \circ \tau = (0\ 1\ 2), since:

Make a program that, given a permutation σ\sigma and a natural kk, computes the power of σ\sigma raised to kk: σk=σ∘…∘σ⏞k)\sigma^k = \overbrace{\sigma \circ \ldots \circ \sigma}^{k)}. By convention, σ0=(0,1,…,n−1)\sigma^{0} = (0, 1, \ldots, n-1).

Input

The input includes several cases. Each case consists in the number nn (1≤n≤1041 \leq n \leq 10^{4}), followed by nn numbers between 11 and nn that describe the permutation σ\sigma, followed by the number kk (0≤k≤1090 \leq k \leq 10^9).

Output

Write the permutation σk\sigma^k.

Observation

The expected solution to this problem has cost O(n⋅log⁡k)O(n \cdot \log k). The solutions that have cost Ω(n⋅k)\Omega(n \cdot k) can get at most 33 points over 1010.

You can add (few) lines of comments explaining what you intend to do.

If needed, you can use that the product of permutations is associative.

Problem information

Author: Enric Rodríguez

Generation: 2026-01-25T15:50:15.949Z

© Jutge.org, 2006–2026.
https://jutge.org