String Decoding

Interview

Time limit1sMemory limit128 MB

Summary
Given a string, a permutation, and a large repetition count m, recover the string that the permutation maps to the given encoded string.
Level

Medium7 of 10

Topics
Math, Implementation, String, Simulation
Solved
No attempts yet

Problem

There is a method for encoding a string, described below.

Let the characters of the string to be encoded be x1,x2,…,xnx_1, x_2, \dots, x_n in order. Encoding follows this procedure.

  1. Choose a natural number mm and a permutation p1,p2,…,pnp_1, p_2, \dots, p_n made of the nn distinct numbers of the set {1,2,…,n}\{1, 2, \dots, n\}.
  2. Repeat step 3 below exactly mm times.
  3. For every 1≤i≤n1 \le i \le n, set yi=xpiy_i = x_{p_i}, then replace each xix_i with yiy_i. (That is, in one step the ii-th character of the new string becomes the pip_i-th character of the previous string.)

For example, encoding the string "hello" with m=3m = 3 and the permutation p=(2,3,1,5,4)p = (2, 3, 1, 5, 4) transforms it as follows.

"hello" → "elhol" → "lhelo" → "helol"

Given the encoded string together with the mm and the permutation p1,…,pnp_1, \dots, p_n used for encoding, write a program that recovers (decodes) the original string from before encoding.

Input

The input consists of several test cases.

The first line of each test case contains two integers nn and mm. (1≤n≤801 \le n \le 80, 1≤m≤1091 \le m \le 10^9)

The second line contains the nn distinct integers p1,p2,…,pnp_1, p_2, \dots, p_n used for encoding. (1≤pi≤n1 \le p_i \le n)

The third line contains the encoded string. Its length is nn, and it may contain spaces.

The last line of the input contains two zeros, and this line is not processed.

Output

For each test case, print the decoded original string on its own line.

Examples1

  1. Example 1

    Input
    5 3
    2 3 1 5 4
    helol
    16 804289384
    13 10 2 7 8 1 16 12 15 6 5 14 3 4 11 9
    scssoet tcaede n
    8 12
    5 3 4 2 1 8 6 7
    encoded?
    0 0
    
    Expected output
    hello
    second test case
    encoded?