shil-and-crazy-operation

Shil likes to perform Crazy Operation on an array A1,A2,...AN.

Given an array A1,A2,...AN and permutation P1,P2, ..,PN, a Crazy Operation consists of two parts:  

Perform Operation Bi = Ai for every i in 1..N

Perform Operation Ai = BPi  for every i in 1..N. Here P is a permutation from 1 to N.

Shil asks you to print the resulting array A1, A2,...AN after doing  Crazy Operation on  it , T times.

Input format:
The first line of input consists of two integers N and T. The next line consists of N integers  A1, A2,...AN. The next line consists of permutation P1,P2,...PN.

Output format:
Print the resulting A1,A2,...AN after doing  Crazy operations on it T times.

Constraints:
1≤N≤10^5
1≤T≤10^18
1≤Ai≤10^9

SAMPLE INPUT
5 3
1 2 3 4 5
3 4 5 2 1

SAMPLE OUTPUT
1 4 3 2 5

Explanation

On doing Crazy Operation 1st time resulting array will be (3,4,5,2,1).
On doing second time , resulting array will be (5,2,1,4,3).
On doing third time, resulting array will be (1,4,3,2,5).

Source: hackerearth | Difficulty: MEDIUM
Tags: Graph algorithms

Implementation


Solutions:
n,t=list(map(int,input().split()))
a=[0]+list(map(int,input().split()))
p=[0]+list(map(int,input().split()))
q=[i for i in range(n)]

def app(p,x):
	res=[0]*len(p)
	for i in range(len(p)):
		res[i]=x[p[i]]
	return res	

while t>0:
	if t%2: a=app(p,a)
	p=app(p,p)
	t/=2
print(" ".join(map(str,a[1:])))