def modinv(x, m): for i in range(m): if (x*i-1) % m == 0: return i def solve(): N,p = map(int,input().split()) A = [0] + list(map(int,input().split())) # サイクルを長さごとに列挙 groups = [[] for _ in range(N+1)] seen = [False]*(N+1) for i in range(1,N+1): if seen[i]: continue v = [] while not seen[i]: seen[i] = True; v.append(i) i = A[i]; groups[len(v)].append(v); # 構築 B = [0]*(N+1) for (L,cycles) in enumerate(groups): if not cycles: continue if L % 2 == 1: d = modinv(2*p,L); while cycles: v = cycles.pop() for k in range(L): B[v[k]] = v[(k-d)%L] else: d = modinv(p,L); while len(cycles) > 1: u = cycles.pop() v = cycles.pop() for k in range(L): B[u[k]] = v[k] B[v[k]] = u[(k-d)%L] if cycles: d = modinv(2*p,L-1); v = cycles.pop() for k in range(L): B[v[k]] = v[(k-d)%(L-1)]; print(*B[1:]) for _ in range(int(input())): solve()