Powers of permutations X39049


Statement
 

pdf   zip

Given an nn, a permutation of {0,1,n1}\{0, 1, \ldots n-1\} is a sequence where each of the numbers 0,1,n10, 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,,σn1)\sigma = (\sigma_{0}, \ldots, \sigma_{n-1}) and τ=(τ0,,τn1)\tau = (\tau_{0}, \ldots, \tau_{n-1}) of {0\{0, 11, n1\ldots n-1 }\}, their product στ\sigma \circ \tau is defined as the permutation ρ=(ρ0,,ρn1)\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:

  • τ0=2\tau_{0} = 2 and σ2=0\sigma_{2} = 0,

  • τ1=0\tau_{1} = 0 and σ0=1\sigma_{0} = 1, and

  • τ2=1\tau_{2} = 1 and σ1=2\sigma_{1} = 2.

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,,n1)\sigma^{0} = (0, 1, \ldots, n-1).

Input

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

Output

Write the permutation σk\sigma^k.

Observation

The expected solution to this problem has cost O(nlogk)O(n \cdot \log k). The solutions that have cost Ω(nk)\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.

Public test cases
  • Input

    3
    1 2 0
    0
    
    3
    1 2 0
    2
    
    4
    0 2 3 1
    1
    
    10
    4 3 7 8 0 5 2 1 6 9
    5
    

    Output

    0 1 2
    2 0 1
    0 2 3 1
    4 7 6 1 0 5 8 2 3 9
    
  • Information
    Author
    Enric Rodríguez
    Language
    English
    Translator
    Original language
    Catalan
    Other languages
    Catalan
    Official solutions
    C++
    User solutions
    C++