The only difference between easy and hard versions is constraints.

There are $n$ kids, each of them is reading a unique book. At the end of any day, the $i$-th kid will give his book to the $p_i$-th kid (in case of $i = p_i$ the kid will give his book to himself). It is guaranteed that all values of $p_i$ are distinct integers from $1$ to $n$ (i.e. $p$ is a permutation). The sequence $p$ doesn't change from day to day, it is fixed.

For example, if $n=6$ and $p=[4, 6, 1, 3, 5, 2]$ then at the end of the first day the book of the $1$-st kid will belong to the $4$-th kid, the $2$-nd kid will belong to the $6$-th kid and so on. At the end of the second day the book of the $1$-st kid will belong to the $3$-th kid, the $2$-nd kid will belong to the $2$-th kid and so on.

Your task is to determine the number of the day the book of the $i$-th child is returned back to him for the first time for every $i$ from $1$ to $n$.

Consider the following example: $p = [5, 1, 2, 4, 3]$. The book of the $1$-st kid will be passed to the following kids:  after the $1$-st day it will belong to the $5$-th kid,  after the $2$-nd day it will belong to the $3$-rd kid,  after the $3$-rd day it will belong to the $2$-nd kid,  after the $4$-th day it will belong to the $1$-st kid. 

So after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day.

You have to answer $q$ independent queries.


-----Input-----

The first line of the input contains one integer $q$ ($1 \le q \le 200$) — the number of queries. Then $q$ queries follow.

The first line of the query contains one integer $n$ ($1 \le n \le 200$) — the number of kids in the query. The second line of the query contains $n$ integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$, all $p_i$ are distinct, i.e. $p$ is a permutation), where $p_i$ is the kid which will get the book of the $i$-th kid.


-----Output-----

For each query, print the answer on it: $n$ integers $a_1, a_2, \dots, a_n$, where $a_i$ is the number of the day the book of the $i$-th child is returned back to him for the first time in this query.


-----Example-----
Input
6
5
1 2 3 4 5
3
2 3 1
6
4 6 2 1 5 3
1
1
4
3 4 1 2
5
5 1 2 4 3

Output
1 1 1 1 1 
3 3 3 
2 3 3 2 1 3 
1 
2 2 2 2 
4 4 4 1 4

Difficulty: EASY
Tags: Spanning trees

Mathematics

Starter code:

Solutions:
import sys
input = sys.stdin.readline
for _ in range(int(input().rstrip())):
	n = int(input().rstrip())
	p = list(map(int, input().rstrip().split()))
	tmp = [i for i in range(1, n + 1)]
	result = [0] * n
	cnt = 0
	while result.__contains__(0):
		tmp2 = tmp.copy()
		for i in range(n):
			tmp[p[i] - 1] = tmp2[i]
		cnt += 1
		for i in range(n):
			if tmp[i] == i + 1 and result[i] == 0:
				result[i] = cnt
	print(*result)


from collections import defaultdict
q = int(input())
for _ in range(q):
	n = int(input())
	l = [0] + list(map(int, input().split()))
	boo = defaultdict(bool)
	ans = [0] * (n + 1)
	for i in range(1, n + 1):
		z = i
		seti = set()
		while boo[z] == False:
			seti.add(z)
			boo[z] = True
			z = l[z]
		for j in seti:
			ans[j] = len(seti)
	print(*ans[1:])


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	x = [0] * n
	t = 0
	while t < n:
		q = k = a[t]
		p = 1
		while 1:
			if a[k - 1] == q:
				x[t] = p
				break
			else:
				k = a[k - 1]
				p += 1
		t += 1
	print(*x)


t = int(input())
q = []
for _ in range(t):
	n = int(input())
	a = [0] + list(map(int, input().split()))
	f = [0] * (n + 1)
	avail = [1] * (n + 1)
	t = [0] * (n + 1)

	def dfs(s):
		global q
		avail[s] = 0
		q.append(s)
		if avail[a[s]] == 1:
			dfs(a[s])
		else:
			res = len(q)
			for i in q:
				f[i] = res
			q = []
	for i in range(1, n + 1):
		if avail[i] == 1:
			dfs(i)
	for i in range(1, n + 1):
		print(f[i], end=' ')
	print()


tc = int(input())
for _ in range(tc):
	n = int(input())
	p = list(map(int, input().split()))
	for i in range(n):
		ans = 1
		pos = p[i]
		while pos != i + 1:
			ans += 1
			pos = p[pos - 1]
		print(ans, end=' ')
	print()


q = int(input())
for i in range(q):
	n = int(input())
	a = [int(i) for i in input().split()]
	ans = [0] * n
	for i in range(n):
		if ans[i] == 0:
			numbers_now = []
			now = a[a[i] - 1]
			numbers_now.append(i)
			numbers_now.append(a[i] - 1)
			count = 1
			while now != a[i]:
				now = a[now - 1]
				numbers_now.append(now - 1)
				count += 1
			for i in numbers_now:
				ans[i] = count
		else:
			continue
	print(*ans)


from sys import stdin, stdout
input = stdin.readline

def listofZeros(n):
	lstzero = [0] * n
	return lstzero

def fn(lst, ans):
	for i in range(len(lst)):
		if ans[i] == 0:
			count = 1
			j = lst[i]
			cycle = [i]
			while not i == j:
				j = lst[j]
				count += 1
				cycle.append(j)
			for el in cycle:
				ans[el] = count
	return ans
for kase in range(int(input())):
	n = int(input())
	lst = [int(x) - 1 for x in input().split()]
	ans = listofZeros(n)
	ans = fn(lst, ans)
	print(*ans)


for i in range(int(input())):
	n = int(input())
	A = list(map(int, input().split()))
	B = [0] * n
	for i in range(n):
		if B[i] == 0:
			m = A[i] - 1
			B[i] = 1
			while m != i:
				B[i] += 1
				m = A[m] - 1
			m = A[i] - 1
			while m != i:
				B[m] = B[i]
				m = A[m] - 1
	for i in B:
		print(i, end=' ')


for i in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	a = [0] * n
	for i in range(n):
		if not a[i]:
			pos = l[i] - 1
			ans = 1
			while pos != i:
				ans += 1
				pos = l[pos] - 1
			a += str(ans) + ' '
			a[i] = ans
			pos = l[i] - 1
			while pos != i:
				a[pos] = ans
				pos = l[pos] - 1
	for i in range(n):
		print(a[i], end=' ')
	print()


for _ in range(int(input())):
	n_kids = int(input())
	l = list(map(int, input().split()))
	res = [None] * n_kids
	days = 1
	for i in range(n_kids):
		if not res[i]:
			if l[i] == i + 1:
				res[i] = 1
				continue
			else:
				cycle = [l[i]]
				while cycle[-1] != i + 1:
					days += 1
					cycle.append(l[cycle[-1] - 1])
				for e in cycle:
					res[e - 1] = days
				days = 1
	print(*res)


import sys

def main():
	for _ in range(int(input())):
		n = int(sys.stdin.readline())
		l = [int(x) for x in sys.stdin.readline().split()]
		k = []
		for i in range(n):
			l[i] = l[i] - 1
		for i in range(n):
			c = 1
			x = l[i]
			while x != i:
				c += 1
				x = l[x]
			k.append(c)
		for i in k:
			print(i, end=' ')
		print()
main()


import re

def read(t=int):
	return list(map(t, input().strip().split(' ')))
q = read()[0]

def check(lis):
	...
while q > 0:
	q -= 1
	n = read()[0]
	p = [None] + read()
	ans = [-1 for i in p]
	for i in range(1, len(p)):
		if ans[i] != -1:
			...
		else:
			stack = [i]
			day = 0
			while True:
				now = p[stack[-1]]
				day += 1
				if now == i:
					break
				else:
					if ans[now] != -1:
						day += ans[now]
						break
					stack.append(now)
			for k in stack:
				ans[k] = day
		print('{} '.format(ans[i]), end='')
	print()


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	ans = [0] * n
	cnt = 0
	loop = [0] * n
	temp = []
	for i in range(n):
		if loop[i] == 0:
			start = i
			while loop[start] == 0:
				loop[start] = 1
				temp.append(start)
				start = arr[start] - 1
				cnt += 1
			for j in temp:
				ans[j] = cnt
			temp = []
			cnt = 0
	print(*ans)


from sys import stdin
cin = stdin.readline
for _ in range(int(cin())):
	n = int(cin())
	a = list(map(int, cin().split()))
	result = [-1] * (n + 1)
	for i in range(n):
		if result[i + 1] != -1:
			continue
		(x, y, cnt) = (-1, i + 1, 0)
		visited = []
		while x != i + 1:
			x = a[y - 1]
			y = x
			cnt += 1
			visited.append(x)
		for child in visited:
			result[child] = cnt
	for i in range(1, n + 1):
		print(result[i], end=' ')
	print()


tc = int(input())
for _ in range(tc):
	n = int(input())
	a = [int(i) - 1 for i in input().split()]
	ans = [0 for i in range(n)]
	for i in range(n):
		count = 0
		j = i
		while i != a[j]:
			j = a[j]
			count = count + 1
		ans[i] = count + 1
	for i in range(n):
		print(ans[i], end=' ')
	print()


t = int(input())
for z in range(t):
	n = int(input())
	a = list(map(int, input().strip().split()))
	op = [0] * n
	vis = [0] * n
	for i in range(n):
		if vis[i] == 1:
			continue
		c = 1
		x = a[i] - 1
		vis[x] = 1
		visi = [x]
		while x != i:
			x = a[x] - 1
			vis[x] = 1
			visi.append(x)
			c += 1
		for j in visi:
			op[j] = c
	print(' '.join(list(map(str, op))))


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr = [-1] + arr
	ans = [-1] * n
	for i in range(1, n + 1):
		if ans[i - 1] == -1:
			temp = set([i, arr[i]])
			cur = arr[i]
			count = 0
			while True:
				count += 1
				cur = arr[cur]
				temp.add(cur)
				if cur == arr[i]:
					break
			for pt in temp:
				ans[pt - 1] = count
	print(*ans)


import math
import sys
from collections import defaultdict, Counter
from itertools import groupby
rt = lambda : map(int, input().split())
ri = lambda : int(input())
rl = lambda : list(map(int, input().split()))

def main():
	q = ri()
	for _ in range(q):
		n = ri()
		a = rl()
		res = [-1] * n
		for i in range(n):
			days = 0
			at = a[i] - 1
			while at != i:
				at = a[at] - 1
				days += 1
			res[i] = days
		print(*[d + 1 for d in res])
main()


def f():
	for _ in range(int(input())):
		n = int(input())
		ll = list(map(int, input().split()))
		a = []
		for i in range(1, n + 1):
			x = i
			c = 1
			t = i
			while 1:
				x = t
				if i == ll.index(x) + 1:
					break
				t = ll.index(x) + 1
				c += 1
			a.append(c)
		print(*a)
f()


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	for i in range(n):
		if arr[i] == i + 1:
			print(1, end=' ')
		else:
			cnt = 2
			var = arr[i]
			while arr[var - 1] != i + 1:
				var = arr[var - 1]
				cnt += 1
			print(cnt, end=' ')
	print()


def books(arr):
	i = 0
	ans = []
	while i < len(arr):
		tmp = [0] + arr
		cur = arr[i]
		ori = arr[i]
		pre = 0
		count = 0
		while True:
			pre = tmp[cur]
			count += 1
			if pre == ori:
				ans.append(str(count))
				break
			cur = pre
		i += 1
	fin = ' '.join(ans)
	print(fin)
q = int(input())
for i in range(q):
	n = int(input())
	x = list(map(int, input().rstrip().split()))
	books(x)


t = int(input())

def dfs(i):
	k = []
	s = [i]
	while s:
		x = s.pop()
		v[x] = True
		k.append(x)
		if p[x] != i:
			s.append(p[x])
	an = len(k)
	for j in k:
		ans[j] = an
for _ in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	p = [i - 1 for i in p]
	ans = [1 for i in range(n)]
	v = [False for i in range(n)]
	for i in range(n):
		if v[i]:
			continue
		dfs(i)
	print(*ans)


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	d = 1
	c = 0
	for j in range(1, n + 1):
		c += 1
		k = a[j - 1]
		d = 1
		while a[j - 1] != c:
			j = a[j - 1]
			d += 1
		print(d, end=' ')
	print(end='\n')


import sys

def rint():
	return map(int, sys.stdin.readline().split())

def input():
	return sys.stdin.readline().rstrip('\n')

def oint():
	return int(input())
q = oint()
for _ in range(q):
	n = oint()
	p = list(rint())
	ans = []
	for i in range(n):
		cur = p[i]
		cnt = 1
		while cur != i + 1:
			cur = p[cur - 1]
			cnt += 1
		ans.append(cnt)
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	ans = [0] * n
	for i in range(n):
		count = 1
		temp = p[i] - 1
		visited = [temp]
		if not ans[i]:
			while p[i] != p[temp]:
				temp = p[temp] - 1
				count += 1
				visited.append(temp)
			for ind in visited:
				ans[ind] = count
			ans[i] = count
	print(*ans)


def dfs(list, u, visited, count, p):
	visited[u] = 1
	while visited[list[u] - 1] == 0:
		count += 1
		parent[list[u] - 1] = p
		visited[list[u] - 1] = 1
		u = list[u] - 1
	return count
for i in range(int(input())):
	n = int(input())
	o = input()
	mylist = list(map(int, o.split(' ')))
	visited = [0] * n
	parent = [0] * n
	ans = [0] * n
	for j in range(n):
		if visited[j] == 0:
			parent[j] = j
			c = dfs(mylist, j, visited, 1, j)
			ans[j] = c
	for j in parent:
		print(ans[j], end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	res = [None] * n
	l = [int(t) for t in input().split()]
	for i in range(n):
		if res[i]:
			continue
			print('MARK')
		if l[i] == i + 1:
			res[i] = 1
			continue
		else:
			index_next_kid = l[i] - 1
			cycle = {i}
			while index_next_kid not in cycle:
				cycle.add(index_next_kid)
				index_next_kid = l[index_next_kid] - 1
			for j in cycle:
				res[j] = len(cycle)
	print(*res)


import math
from collections import deque, defaultdict
from sys import stdin, stdout
input = stdin.readline
listin = lambda : list(map(int, input().split()))
mapin = lambda : map(int, input().split())
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	for i in range(n):
		a[i] -= 1
	col = [0 for i in range(n)]
	c = 1
	for i in range(n):
		if not col[i]:
			s = i
			while col[s] == 0:
				col[s] = c
				s = a[s]
			c += 1
	d = defaultdict(int)
	for i in col:
		d[i] += 1
	ans = [0 for i in range(n)]
	for i in range(n):
		ans[i] = d[col[i]]
	print(*ans)


def read():
	return list(map(int, input().split()))
q = int(input())
for test in range(q):
	n = int(input())
	a = read()
	for i in range(n):
		a[i] -= 1
	used = [False] * n
	ans = [0] * n
	for i in range(n):
		if not used[i]:
			j = a[i]
			k = 1
			while j != i:
				k += 1
				j = a[j]
			j = a[i]
			ans[i] = k
			while j != i:
				j = a[j]
				ans[j] = k
				used[j] = True
	print(*ans)


import sys
input = sys.stdin.readline

class Unionfind:

	def __init__(self, n):
		self.par = [-1] * n
		self.rank = [1] * n

	def root(self, x):
		if self.par[x] < 0:
			return x
		self.par[x] = self.root(self.par[x])
		return self.par[x]

	def unite(self, x, y):
		(rx, ry) = (self.root(x), self.root(y))
		if rx != ry:
			if self.rank[rx] >= self.rank[ry]:
				self.par[rx] += self.par[ry]
				self.par[ry] = rx
				if self.rank[rx] == self.rank[ry]:
					self.rank[rx] += 1
			else:
				self.par[ry] += self.par[rx]
				self.par[rx] = ry

	def is_same(self, x, y):
		return self.root(x) == self.root(y)

	def count(self, x):
		return -self.par[self.root(x)]
q = int(input())
for _ in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	uf = Unionfind(n)
	for i in range(n):
		uf.unite(i, a[i] - 1)
	ans_l = []
	for i in range(n):
		ans_l.append(uf.count(i))
	print(*ans_l)


q = int(input())
for i in range(q):
	n = int(input())
	p_seq = list(map(int, input().split()))
	p_seq = [x - 1 for x in p_seq]
	anslist = [0 for b in range(n)]
	ansboolean = [False for c in range(n)]
	for a in range(n):
		if not ansboolean[a]:
			ans = 1
			person_to_pass = p_seq[a]
			ansboolean[a] = True
			while person_to_pass != a:
				ansboolean[person_to_pass] = True
				person_to_pass = p_seq[person_to_pass]
				ans += 1
			person_to_pass = p_seq[a]
			anslist[a] = ans
			while person_to_pass != a:
				anslist[person_to_pass] = ans
				person_to_pass = p_seq[person_to_pass]
	print(' '.join([str(x) for x in anslist]))


def find(x):
	while x != link[x]:
		link[x] = link[link[x]]
		x = link[x]
	return x

def same(x, y):
	return find(x) == find(y)

def union(x, y):
	global size, link
	x = find(x)
	y = find(y)
	if x != y:
		if size[x] > size[y]:
			size[x] += size[y]
			link[y] = x
		else:
			size[y] += size[x]
			link[x] = y
for _ in range(int(input())):
	n = int(input())
	link = list(map(int, input().split()))
	for i in range(n):
		link[i] -= 1
	size = [1 for i in range(n)]
	for i in range(n):
		link[i] = find(link[i])
	this = {}
	for i in list(set(link)):
		this[i] = link.count(i)
	ans = []
	for i in link:
		ans.append(this[i])
	print(*ans)


q = int(input())
for i in range(q):
	n = int(input())
	arr = list(map(int, input().split()))
	for i in range(n):
		arr[i] = [arr[i], 0]
	for i in range(n):
		if arr[i][1] == 0:
			l = [i]
			p = arr[i][0] - 1
			k = 1
			while i != p:
				k += 1
				l.append(p)
				p = arr[p][0] - 1
			for j in range(len(l)):
				arr[l[j]][1] = k
	for i in range(n):
		print(arr[i][1], end=' ')


import sys, os.path
from collections import *
from copy import *
import math
mod = 10 ** 9 + 7
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
for q in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	res = [0 for i in range(n)]
	for i in range(n):
		temp = []
		count = 1
		j = i
		if res[j] == 0:
			while a[j] != i + 1:
				count += 1
				j = a[j] - 1
				temp.append(a[j])
			res[i] = count
			if temp:
				for i in temp:
					res[i - 1] = count
	print(*res)


q = int(input())
for _ in range(q):
	n = int(input())
	perm = list(map(int, input().split()))
	remain = set(perm)
	result = {i + 1: 0 for i in range(n)}
	while len(remain) > 0:
		m = remain.pop()
		cycle = [m]
		while True:
			m = perm[m - 1]
			if m not in remain:
				break
			remain.remove(m)
			cycle.append(m)
		k = len(cycle)
		for j in cycle:
			result[j] = str(k)
	print(' '.join(result.values()))


def task_2_complex(childrens, values):
	answer = [0] * childrens
	first_row = list(range(1, childrens + 1))
	for i in range(1, childrens + 1):
		if answer[i - 1] != 0:
			continue
		cycle = 1
		if first_row[i - 1] == values[i - 1]:
			answer[i - 1] = cycle
		else:
			index = values[i - 1]
			cycle_indexes = list()
			while index != i:
				index = values[index - 1]
				cycle_indexes.append(index)
				cycle += 1
			for j in cycle_indexes:
				answer[j - 1] = cycle
	print(*answer)
q = int(input())
for q in range(q):
	(childrens,) = map(int, input().rstrip().split())
	values = list(map(int, input().rstrip().split()))
	task_2_complex(childrens, values)


h = int(input())
for _ in range(h):
	n = int(input())
	ar = [int(i) for i in input().split(' ')]
	d = dict()
	for i in range(1, n + 1):
		d[i] = -1
	for i in range(1, n + 1):
		if d[i] == -1:
			val = ar[i - 1]
			aa = [i]
			count = 1
			while True:
				if val != i:
					aa.append(val)
					val = ar[val - 1]
					count += 1
				else:
					break
			k = 0
			while k < len(aa):
				d[aa[k]] = count
				k += 1
	for i in d.keys():
		print(str(d[i]), end=' ')
	print()


def find(node):
	cnt = 0
	copy = node
	while p[node] != copy:
		cnt += 1
		node = p[node]
	return cnt + 1
for _ in range(int(input())):
	n = int(input())
	p = [0] + list(map(int, input().split()))
	res = []
	for i in range(1, n + 1):
		res.append(find(i))
	print(' '.join(map(str, res)))


from sys import stdin, stdout
import math, sys, heapq
from itertools import permutations, combinations
from collections import defaultdict, deque, OrderedDict
from os import path
import random
import bisect as bi

def yes():
	print('YES')

def no():
	print('NO')
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

	def I():
		return int(input())

	def In():
		return map(int, input().split())
else:

	def I():
		return int(stdin.readline())

	def In():
		return map(int, stdin.readline().split())

def dict(a):
	d = {}
	for x in a:
		if d.get(x, -1) != -1:
			d[x] += 1
		else:
			d[x] = 1
	return d

def find_gt(a, x):
	i = bi.bisect_left(a, x)
	if i != len(a):
		return i
	else:
		return -1

def main():
	try:
		n = I()
		l = [0]
		l += list(In())
		ans = []
		for x in range(1, n + 1):
			count = 1
			temp = x
			while l[temp] != x:
				count += 1
				temp = l[temp]
			ans.append(count)
		print(*ans)
	except:
		pass
M = 998244353
P = 1000000007
for _ in range(I()):
	main()


test_num = int(input())
result = []
for num in range(test_num):
	iChild = range(int(input()))
	pChild = input().split(' ')
	res = ''
	Tbook = 1
	for x in iChild:
		Tbook = x
		daysN = 0
		while True:
			Tbook = int(pChild[Tbook]) - 1
			daysN += 1
			if Tbook == x:
				break
		res += str(daysN) + ' '
	result.append(res)
for x in result:
	print(x)


def solve():
	n = int(input())
	p = list(map(int, input().split()))
	ans = [0] * n
	for i in range(n):
		d = 0
		j = p[i] - 1
		d += 1
		while j != i:
			d += 1
			j = p[j] - 1
		ans[i] = str(d)
	print(' '.join(ans))
for _ in range(int(input())):
	solve()


q = int(input())
for _ in range(q):
	n = int(input())
	a = [int(i) - 1 for i in input().split()]
	used = [0 for i in a]
	ans = [1 for i in a]
	for i in range(len(a)):
		if used[i] == 0:
			start = i
			i = a[i]
			now = [start]
			used[start] = 1
			while start != i:
				now.append(i)
				used[i] = 1
				i = a[i]
			for j in range(len(now)):
				ans[now[j]] = len(now)
	print(' '.join([str(i) for i in ans]))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	sol = [1] * n
	for i in range(n):
		if a[i] == i + 1:
			continue
		k = a[i] - 1
		every = [k]
		nosteps = 1
		while k != i:
			k = a[k] - 1
			nosteps += 1
			every.append(k)
		for j in every:
			a[j] = j + 1
			sol[j] = nosteps
	print(*sol)


import sys

def readline():
	return input()

def fun(n, p):
	memo = {}
	out = [0] * n
	for i in range(n):
		if i in memo:
			out[i] = str(memo[i])
			continue
		pos = p[i] - 1
		ans = 1
		cycle = []
		cycle.append(i)
		while pos != i:
			cycle.append(pos)
			ans += 1
			pos = p[pos] - 1
		for el in cycle:
			memo[el] = ans
		out[i] = str(ans)
	print(' '.join(out))
q = int(readline())
for i in range(q):
	n = int(readline())
	p = list(map(int, readline().split(' ')))
	fun(n, p)


import math
import bisect
import collections
import itertools
from math import gcd, floor, sqrt, log
from collections import defaultdict as dd, Counter as ctr
from bisect import bisect_left as bl, bisect_right as br
from itertools import permutations as pr, combinations as cb
inp = lambda : int(input())
strng = lambda : input().strip()
jn = lambda x, l: x.join(map(str, l))
strl = lambda : list(input().strip())
mul = lambda : map(int, input().strip().split())
mulf = lambda : map(float, input().strip().split())
seq = lambda : list(map(int, input().strip().split()))

def results(arr, n):
	temp = []
	for i in range(1, n + 1):
		cnt = 0
		pos = arr[i - 1]
		while pos != i:
			cnt += 1
			pos = arr[pos - 1]
		temp.append(cnt + 1)
	return temp

def main():
	t = inp()
	for _ in range(t):
		n = inp()
		a = seq()
		result = results(a, n)
		print(*result)
main()


for _ in range(int(input())):
	n = int(input())
	p = list(map(lambda x: int(x) - 1, input().split()))
	ans = [None] * n
	for i in range(n):
		if ans[i] is None:
			x = p[i]
			stack = [i]
			while x != i:
				stack.append(x)
				x = p[x]
			k = len(stack)
			for x in stack:
				ans[x] = k
	print(*ans)


import sys, math

def input():
	return sys.stdin.readline()[:-1]

def main():
	q = int(input())
	for _ in range(q):
		n = int(input())
		p = list(map(int, input().split()))
		r = [p[k] % n for k in range(n)]
		ans = [0 for k in range(n)]
		for k in range(n):
			temp = p[k]
			t = 1
			while temp != k + 1:
				temp = p[temp - 1]
				t += 1
			ans[k] = t
		print(*ans, sep=' ')
main()


q = int(input())
for _ in range(q):
	n = int(input())
	succ = list(map(lambda x: int(x) - 1, input().split()))
	cycle_belong = [-1 for k in range(n)]
	cycle_size = []
	for k in range(n):
		if cycle_belong[k] == -1:
			start = k
			current = k
			cycle_belong[k] = len(cycle_size)
			size_cycle = 1
			while succ[current] != start:
				size_cycle += 1
				cycle_belong[current] = len(cycle_size)
				current = succ[current]
			cycle_belong[current] = len(cycle_size)
			cycle_size.append(size_cycle)
	print(' '.join(map(lambda x: str(cycle_size[cycle_belong[x]]), range(n))))


q = int(input())
for _ in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	b = list()
	for i in range(n):
		b.append(0)
	for i in range(n):
		j = i + 1
		cn = 0
		w = a[i]
		if a[i] == j:
			cn = 1
		else:
			cn = 2
		while a[w - 1] != j:
			w = a[w - 1]
			cn += 1
		b[i] = cn
	print(*b)


from sys import stdin, stdout
x = int(stdin.readline())

def count(i, L):
	k = L[i] - 1
	return k
for a in range(x):
	q = stdin.readline()
	L = list(map(int, stdin.readline().split()))
	for b in range(len(L)):
		c = 0
		f = True
		ans = b
		while f == True:
			ans = count(ans, L)
			c += 1
			if ans == b:
				f = False
		print(c, end=' ')
	print()


from sys import stdin, stdout
from os import path
rd = lambda : stdin.readline().strip()
wr = stdout.write
if path.exists('input.txt'):
	stdin = open('input.txt', 'r')
for _ in range(int(rd())):
	x = int(rd())
	mylist = list(map(int, rd().split()))
	mylist.insert(0, 0)
	arr = []
	for i in range(1, x + 1):
		j = i
		count = 1
		while True:
			if mylist[j] == i:
				break
			else:
				j = mylist[j]
				count += 1
		arr.append(count)
	print(*arr)


n = int(input())
for queries in range(n):
	no_of_children = int(input())
	children = list(map(lambda x: x - 1, map(int, input().split())))
	final_ans = [0] * no_of_children
	for child in range(no_of_children):
		if final_ans[child] == 0:
			book_original = child
			book_new = children[book_original]
			count = 1
			while book_new != book_original:
				count += 1
				book_new = children[book_new]
			final_ans[book_original] = count
			book_new = children[book_original]
			while book_new != book_original:
				final_ans[book_new] = count
				book_new = children[book_new]
	print(*final_ans)


def f(s_index, index, arr, l, k=0):
	k += 1
	if s_index == index:
		l.append(index)
		return k
	else:
		l.append(index)
		return f(s_index, arr[index][0] - 1, arr, l, k)
q = int(input())
for i in range(q):
	n = int(input())
	arr = list(map(int, input().split()))
	for i in range(n):
		arr[i] = [arr[i], 0]
	for i in range(n):
		if arr[i][1] == 0:
			l = []
			k = f(i, arr[i][0] - 1, arr, l)
			for j in range(len(l)):
				arr[l[j]][1] = k
	for i in range(n):
		print(arr[i][1], end=' ')


import math
q = int(input())
for tt in range(q):
	n = int(input())
	p = list(map(int, input().split()))
	visited = [False] * n
	ans = [0] * n
	for i in range(len(p)):
		p[i] -= 1
	j = 0
	while j < n:
		if not visited[j]:
			curr = []
			while not visited[j]:
				curr.append(j)
				visited[j] = True
				j = p[j]
			for i in curr:
				ans[i] = len(curr)
		j += 1
	for i in ans:
		print(i, end=' ')
	print()


for i in range(int(input())):
	(N, X) = (int(input()), list(map(int, input().split())))
	for j in range(N):
		(Temp, Count) = (X[:], 1)
		while Temp[j] != j + 1:
			(Temp[j], Count) = (Temp[Temp[j] - 1], Count + 1)
		print(Count, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	a = [0] + [int(x) for x in input().split()]
	for i in range(1, n + 1):
		ans = 1
		x = a[i]
		while x != i:
			ans += 1
			x = a[x]
		print(ans, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	for i in range(n):
		j = a[i]
		cnt = 1
		while j <= n and j != i + 1:
			j = a[j - 1]
			cnt += 1
		print(cnt, end=' ')
	print()


t = int(input())
for _ in range(t):
	n = int(input())
	arr = [0] + list(map(int, input().split()))
	res = [0] * (n + 1)
	for i in range(1, n + 1):
		(j, cnt) = (arr[i], 1)
		while j != i:
			j = arr[j]
			cnt += 1
		res[i] = cnt
	print(*res[1:])


def root(a):
	while parent[a] != a:
		parent[a] = parent[parent[a]]
		a = parent[a]
	return a

def union(a, b):
	a = root(a)
	b = root(b)
	if a == b:
		return
	elif size[a] <= size[b]:
		parent[a] = b
		size[b] += size[a]
		size[a] = 0
	else:
		parent[b] = a
		size[a] += size[b]
		size[b] = 0
q = int(input())
while q:
	q -= 1
	n = int(input())
	p = [int(e) for e in input().split()]
	size = [1] * (n + 1)
	parent = [i for i in range(n + 1)]
	for i in range(n):
		union(i + 1, p[i])
	ans = []
	for i in range(n):
		ans.append(size[root(i + 1)])
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	l = []
	for i in range(n):
		c = 1
		val = a[i]
		while val != i + 1:
			val = a[val - 1]
			c += 1
		l.append(c)
	print(*l)


q = int(input())
for c in range(q):
	n = int(input())
	A = list(map(int, input().split()))
	B = A[:]
	C = list()
	for i in range(0, n):
		k = 1
		pos = A[i] - 1
		while pos != A.index(A[i]):
			pos = A[pos] - 1
			k += 1
		C.append(k)
	print(*C)


cases = int(input())
for _ in range(cases):
	n = int(input())
	trans = [int(i) - 1 for i in input().split(' ')]
	for kid in range(n):
		curr = trans[kid]
		count = 1
		while curr != kid:
			curr = trans[curr]
			count += 1
		print(count, end=' ')
	print()


def all_returned(n, p_kids):
	ans = [0 for i in range(n)]
	for i in range(n):
		if not ans[i]:
			pos = p_kids[i]
			met = [pos - 1]
			k = 1
			while pos != i + 1:
				pos = p_kids[pos - 1]
				met.append(pos - 1)
				k += 1
			for j in met:
				ans[j] = k
	return ' '.join([str(i) for i in ans])
q = int(input())
for _ in range(q):
	n = int(input())
	p_kids = [int(i) for i in input().split()]
	print(all_returned(n, p_kids))


def DFS(idx, arr, v_tag, visited):
	visited[idx] = v_tag
	cyc_len = 1
	end = idx
	start = arr[idx] - 1
	while start != end:
		visited[start] = v_tag
		cyc_len += 1
		start = arr[start] - 1
	return (cyc_len, visited)

def solve(arr, n):
	dfs_dict = dict()
	v_tag = 1
	visited = [0 for i in arr]
	for i in range(0, n):
		if visited[i] == False:
			(cyc_len, visited) = DFS(i, arr, v_tag, visited)
			dfs_dict[v_tag] = cyc_len
			v_tag += 1
	for i in range(0, n):
		print(dfs_dict[visited[i]], end=' ')
	print()

def main():
	q = int(input())
	while q:
		q -= 1
		n = int(input())
		arr = [int(i) for i in input().split()]
		solve(arr, n)
	return
main()


import sys
input = sys.stdin.readline
t = int(input())
while t > 0:
	n = int(input())
	a = list(map(int, input().split()))
	ans = [0 for _ in range(n)]
	for i in range(n):
		if ans[i] is 0:
			cur = a[i] - 1
			l = [i]
			cnt = 1
			while cur is not i:
				l.append(cur)
				cur = a[cur] - 1
				cnt += 1
			for j in l:
				ans[j] = str(cnt)
		else:
			continue
	print(' '.join(ans))
	t -= 1


q = int(input())
for i in range(q):
	n = int(input())
	a = [int(i) for i in input().split()]
	ans = [0] * n
	for i in range(n):
		now = a[a[i] - 1]
		count = 1
		while now != a[i]:
			now = a[now - 1]
			count += 1
		ans[i] = count
	print(*ans)


from collections import defaultdict
from math import gcd, sqrt, factorial, ceil
q = int(input())
for _ in range(q):
	n = int(input())
	l = [0] + list(map(int, input().split()))
	ans = [0] * n
	hash = defaultdict(set)
	boo = defaultdict(bool)
	for i in range(1, n + 1):
		if boo[i] == False:
			seti = set()
			boo[i] = True
			z = l[i]
			temp = i
			seti.add(i)
			while boo[z] == False:
				boo[z] = True
				hash[temp].add(z)
				hash[z].add(i)
				seti.add(temp)
				seti.add(z)
				temp = z
				z = l[z]
			z = len(seti)
			for j in seti:
				ans[j - 1] = z
	print(*ans)


import sys
import bisect as bi
import math
from collections import defaultdict as dd
import heapq
import itertools
input = sys.stdin.readline
from random import randint
mo = 10 ** 9 + 7

def cin():
	return map(int, sin().split())

def ain():
	return list(map(int, sin().split()))

def sin():
	return input()

def inin():
	return int(input())
for _ in range(inin()):
	n = inin()
	l = ain()
	vi = [0] * n
	d = dd(list)
	ans = [0] * n
	for i in range(n):
		if vi[i] == 0:
			cur = [i]
			nex = l[i] - 1
			c = 1
			vi[i] = 1
			while nex != i:
				vi[nex] = 1
				cur.append(nex)
				c += 1
				nex = l[nex] - 1
			d[c] += cur
	for (i, j) in d.items():
		for k in j:
			ans[k] = i
	print(*ans)


q = int(input())
while q:
	n = int(input())
	p = input().split()
	for i in range(n):
		p[i] = int(p[i])
	a = [0 for i in range(n)]
	b = []
	for i in range(n):
		if a[i] == 0:
			j = i
			b.append(p[j])
			while b[-1] != i + 1:
				j = p[j] - 1
				b.append(p[j])
			for j in range(len(b)):
				a[b[j] - 1] = len(b)
			b = []
	print(*a)
	q -= 1


import sys
stdin = sys.stdin
ns = lambda : stdin.readline().rstrip()
ni = lambda : int(ns())
na = lambda : list(map(int, stdin.readline().split()))

def root(start, par, reach, c):
	reach.append(par)
	if start == c[par - 1]:
		return reach
	return root(start, c[par - 1], reach, c)

def main():
	q = ni()
	for _ in range(q):
		n = ni()
		a = na()
		ans = [0] * n
		for aa in a:
			reach = []
			res = root(aa, aa, reach, a)
			p = len(set(res))
			for r in res:
				ans[r - 1] = p
		print(*ans)
main()


for _ in range(int(input())):
	n = int(input())
	p = [int(x) for x in input().split()]
	for i in range(n):
		pos = p[i]
		ans = 1
		while pos != i + 1:
			ans += 1
			pos = p[pos - 1]
		print(ans, end=' ')


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

class DSU(object):

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.rank = [1] * n
		self.cycle = False

	def find(self, key):
		if self.parent[key] != key:
			self.parent[key] = self.find(self.parent[key])
		return self.parent[key]

	def union(self, a, b):
		(s1, s2) = (self.find(a), self.find(b))
		if s1 != s2:
			if self.rank[s1] < self.rank[s2]:
				self.parent[s1] = s2
				self.rank[s2] += self.rank[s1]
			else:
				self.parent[s2] = s1
				self.rank[s1] += self.rank[s2]
		else:
			self.cycle = True

	def has_cycle(self):
		return self.cycle

	def show_parent(self):
		return self.parent

	def show_rank(self):
		return self.rank

def main():
	n = int(input())
	a = list(map(int, input().split()))
	d = DSU(n + 1)
	for i in range(n):
		d.union(i + 1, a[i])
	leader = d.show_parent()[1:]
	rank = d.show_rank()[1:]
	ans = []
	for i in range(n):
		ans.append(rank[d.find(a[i]) - 1])
	print(*ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	main()


q = int(input())
while q > 0:
	n = int(input())
	arr = [int(x) for x in input().split()]
	res = []
	d = {}
	for x in range(1, n + 1):
		temp = arr[x - 1]
		flg = False
		for i in range(len(d.values())):
			if temp in list(d.values())[i]:
				res.append(list(d.keys())[i])
				flg = True
				break
		if flg:
			continue
		tl = [temp]
		c = 1
		while x != temp:
			temp = arr[temp - 1]
			tl.append(temp)
			c += 1
		d[c] = tl
		res.append(c)
	print(*res)
	q -= 1


def wczytywanie():
	n = int(input())
	lista = []
	lista_i = []
	for i in range(1, n + 1):
		lista.append(i)
	lista_i = list(map(int, input().split()))
	return (lista, lista_i)

def ile_dni():
	(lista, lista_i) = wczytywanie()
	for i in range(1, len(lista) + 1):
		pozycja = lista_i[i - 1] - 1
		ile_dni = 1
		while pozycja != i - 1:
			ile_dni += 1
			pozycja = lista_i[pozycja] - 1
		print(ile_dni, end=' ')
n = int(input())
for i in range(n):
	ile_dni()
	print()


def read1DArray():
	line = input()
	return [int(i) for i in line.split()]
list1 = []
T = int(input())
for i in range(T):
	length = int(input())
	a = read1DArray()
	for i in range(0, length):
		kid = a[i]
		days = 1
		while i + 1 != kid:
			kid = a[kid - 1]
			days += 1
		list1.append(days)
	print(' '.join((str(x) for x in list1)))
	list1.clear()


def h(x):
	global k
	if r[x] < 1:
		r[x] = 1
		k += 1
		h(a[x] - 1)
		r[x] = k
for _ in [0] * int(input()):
	n = int(input())
	a = (*map(int, input().split()),)
	k = 0
	r = [0] * n
	while n:
		k = 0
		n -= 1
		h(n)
	print(*r)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
ii = lambda : int(input())
kk = lambda : map(int, input().split())
ll = lambda : list(kk())
for _ in range(ii()):
	(n, ls) = (ii(), list(map(lambda x: int(x) - 1, input().split())))
	vis = [0] * n
	for i in range(n):
		if not vis[i]:
			(i2, l) = (ls[i], 1)
			while i2 != i:
				i2 = ls[i2]
				l += 1
			(vis[i], i2) = (l, ls[i])
			while i2 != i:
				vis[i2] = l
				i2 = ls[i2]
	print(*vis)


q = int(input())
for i in range(q):
	n = int(input())
	l = list(map(int, input().split(' ')))
	l.insert(0, 0)
	for x in range(1, n + 1):
		(o, k) = (x, 1)
		while l[o] != x:
			o = l[o]
			k += 1
		print(k, end=' ')
	print('')


from sys import stdin
from collections import deque
from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin

def ii():
	return int(stdin.readline())

def fi():
	return float(stdin.readline())

def mi():
	return map(int, stdin.readline().split())

def fmi():
	return map(float, stdin.readline().split())

def li():
	return list(mi())

def lsi():
	x = list(stdin.readline())
	x.pop()
	return x

def si():
	return stdin.readline()
for _ in range(ii()):
	n = ii()
	res = [0] * (n + 1)
	v = [True] * (n + 1)
	a = [0] + li()
	for i in range(1, n + 1):
		if v[i]:
			s = {i}
			x = i
			while i != a[x]:
				x = a[x]
				s.add(x)
			l = len(s)
			for j in s:
				res[j] = l
				v[j] = False
	print(*res[1:])


def mi():
	return map(int, input().split())
mod = 10 ** 9 + 7
for _ in range(int(input())):
	n = int(input())
	a = list(mi())
	a.insert(0, 0)
	i = 1
	c = [0] * (n + 1)
	cid = 1
	cnt = {}
	while i <= n:
		(q, w) = (i, a[i])
		c[q] = c[w] = cid
		cnt[cid] = 2
		while q != w:
			w = a[w]
			c[w] = cid
			if cid not in cnt:
				cnt[cid] = 0
			cnt[cid] += 1
		cid += 1
		i += 1
	for i in range(1, n + 1):
		print(cnt[c[i]] - 1, end=' ')
	print()


import sys
from math import *
input = sys.stdin.readline
RI = lambda : [int(x) for x in sys.stdin.readline().strip().split()]
rw = lambda : input().strip().split()
ls = lambda : list(input().strip())
from collections import defaultdict as df
import heapq
infinite = float('inf')
t = int(input())
for i in range(t):
	n = int(input())
	l = RI()
	done = [0] * n
	ans = [0] * n
	c = 0
	cur = 0
	while cur < n:
		if done[cur] == 1:
			cur += 1
			continue
		c = 0
		temp = []
		while done[cur] == 0:
			temp.append(cur)
			done[cur] = 1
			cur = l[cur] - 1
			c += 1
		for j in temp:
			ans[j] = c
		cur += 1
	print(*ans, sep=' ')


import sys
sys.setrecursionlimit(200001)
from collections import *

def li():
	return [int(____) for ____ in input().split(' ')]

def val():
	return int(input())
visited = {}
curr = {}
ans = []

def do(tot):
	global curr, ans
	for q in curr:
		ans[q] = tot

def bfs(l, ind, tot, mainind):
	d = deque()
	d.append([ind, tot])
	while d:
		(ind, tot) = d.pop()
		if l[ind] == mainind + 1:
			do(tot)
		else:
			curr[ind] = 1
			visited[l[ind]] = 1
			d.append([l[ind] - 1, tot + 1])
for _ in range(val()):
	n = val()
	l = li()
	visited = {}
	ans = [1 for k in range(n)]
	for i in range(len(l)):
		if l[i] not in visited:
			curr = {}
			bfs(l, i, 1, i)
	print(' '.join((str(arun) for arun in ans)))


for _ in range(int(input())):
	n = int(input())
	l = [int(j) for j in input().split()]
	v = [-1 for i in range(n)]
	ans = [-1 for i in range(n)]
	for i in range(n):
		if v[i] == -1:
			v[i] = 1
			k = l[i] - 1
			c = 1
			l1 = [i]
			while k != i:
				c += 1
				v[k] = 1
				l1.append(k)
				k = l[k] - 1
			for j in l1:
				ans[j] = c
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	a = list(range(1, n + 1))
	b = list(map(int, input().split()))
	c = dict(zip(a, b))
	d = [0] * (n + 1)
	for i in range(1, n + 1):
		if d[i] == 0:
			e = [i]
			f = e[-1]
			while c[f] not in e:
				e.append(c[f])
				f = e[-1]
			n1 = len(e)
			for j in e:
				d[j] = str(n1)
		else:
			pass
	print(' '.join(d[1:]))


q = int(input())
for i in range(q):
	n = int(input())
	lis = [0] * n
	a = list(map(int, input().split()))
	q = []
	ind = 0
	now = 0
	end = 0
	while end < n:
		while ind < n:
			if lis[ind] == 0:
				now = ind
				break
			ind += 1
		q = []
		while len(q) == 0 or now != q[0]:
			q.append(now)
			now = a[now] - 1
		for i in q:
			lis[i] = len(q)
		end += len(q)
	print(' '.join(map(str, lis)))


q = int(input())
while q > 0:
	n = int(input())
	p = list(map(int, input().split()))
	res = [1] * n
	for i in range(n):
		if res[i] == 1:
			a = p[i]
			ls = [a]
			while a != i + 1:
				a = p[a - 1]
				ls.append(a)
				res[i] += 1
			for k in ls:
				res[k - 1] = res[i]
	print(*res)
	q -= 1


n = int(input())
for x in range(n):
	k = int(input())
	l = [int(x) - 1 for x in input().split()]
	d = [-1 for x in range(k)]
	dd = [-1 for x in range(k)]
	for i in range(k):
		if d[i] != -1:
			continue
		r = 1
		j = l[i]
		while True:
			dd[r - 1] = j
			if i == j:
				for t in range(r):
					d[dd[t]] = r
				break
			j = l[j]
			r += 1
	print(*d)


for _ in range(int(input())):
	kids = int(input())
	order = list(map(int, input().split()))
	re = []
	for j in range(1, kids + 1):
		idx = order[j - 1]
		days = 1
		while j != idx:
			temp = order[idx - 1]
			idx = temp
			days += 1
		re.append(days)
	print(*re)


import sys
q = int(input())
for x in range(q):
	n = int(input())
	p = [int(i) for i in input().split()]
	arr = [0] * n
	for i in range(n):
		ch = p[i]
		count = 0
		while ch != i + 1:
			ch = p[ch - 1]
			count += 1
		arr[i] = count
	for g in range(n):
		print(arr[g] + 1, end=' ')
	print()


import sys
input = sys.stdin.readline
tc = int(input())
for _ in range(tc):
	n = int(input())
	arr = list(map(int, input().split()))
	ans = [0 for _ in range(n)]
	i = 0
	while i < n:
		if ans[i] == 0:
			checker = list()
			tmp = arr[i] - 1
			cnt = 1
			while tmp != i:
				checker.append(tmp)
				tmp = arr[tmp] - 1
				cnt += 1
			ans[i] = cnt
			for j in checker:
				ans[j] = cnt
			i += 1
		else:
			i += 1
			continue
	for i in ans:
		print(i, end=' ')
	print()


q = int(input())
for _ in range(q):
	n = int(input())
	p = [0] + [int(i) for i in input().split()]
	book = {i: 0 for i in range(1, n + 1)}
	res = [0] * (n + 1)
	ans = [0] * (n + 1)
	count = [0] * (n + 1)
	for i in range(1, n + 1):
		book[i] = p[i]
		count[i] += 1
	for i in range(1, n + 1):
		j = book[i]
		while i != j:
			j = book[j]
			count[i] += 1
		ans[i] = count[i]
	print(*ans[1:])


import sys
input = lambda : sys.stdin.readline()
MOD = 1000000007
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : list(map(int, input().split()))
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())
for _ in range(ii()):
	n = ii()
	l = il()
	lvis = [0] * (n + 1)
	d = dict()
	for i in range(1, n + 1):
		d[i] = l[i - 1]
	lcomp = []
	for i in range(1, n + 1):
		if not lvis[i]:
			lvis[i] = 1
			s = {i}
			x = d[i]
			while i != x:
				s.add(x)
				x = d[x]
				lvis[x] = 1
			lcomp.append(s)
	for i in lcomp:
		for j in i:
			lvis[j] = len(i)
	for i in range(1, n + 1):
		print(lvis[i], end=' ')
	print()


from math import *
from sys import *
from heapq import *
from collections import defaultdict
from itertools import permutations
import os, sys
from io import IOBase, BytesIO
M = 10 ** 9 + 7

def graph_as_tree_1_root():
	n = int(input())
	dict = defaultdict(list)
	for _ in range(n - 1):
		(x, y) = list(map(int, input().split()))
		dict[x].append(y)
		dict[y].append(x)
	tree = [[1]]
	temp = [1]
	vall = 0
	seen = set([i for i in range(2, n + 1)])
	lol = []
	while len(seen) > 0:
		lol = list(seen)
		tt = []
		for x in temp:
			aa = []
			for val in dict[x]:
				if val in seen:
					aa += [val]
					seen.remove(val)
			dict[x] = aa
			tt += aa
		tree.append(tt)
		temp = tt
		vall += 1
	for x in lol:
		dict[x] = []
	print(tree, dict)

def pow(a, b):
	res = 1
	while b > 0:
		if b & 1:
			res *= a
		a *= a
		b >>= 1
	return res

def powmod(a, b, m):
	res = 1
	while b > 0:
		if b & 1:
			res = res * a % m
		a = a * a % m
		b //= 2
	return res

def inv(a, m):
	return powmod(a, m - 2, m)

def alldivisors(n):
	list = []
	arr = []
	for i in range(1, int(sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				arr += [i]
			else:
				arr += [i]
				list.append(n // i)
	arr += list[::-1]
	return arr

def primefactorisation(n):
	potentional_p = 3
	itog_list = defaultdict(int)
	if n % 2 == 0:
		itog_list[2] = 0
	while n % 2 == 0:
		n = n // 2
		itog_list[2] += 1
	while n - 1:
		if potentional_p > n ** 0.5:
			itog_list[n] += 1
			return itog_list
		while n % potentional_p == 0:
			n = n // potentional_p
			itog_list[potentional_p] += 1
		potentional_p += 2
	return itog_list

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		dict = defaultdict(int)
		for i in range(n):
			dict[i + 1] = a[i]
		vis = [0] * n
		for i in range(1, n + 1):
			if vis[i - 1] != 0:
				continue
			st = []
			val = dict[i]
			st += [i, val]
			res = 1
			while val != i:
				val = dict[val]
				st += [val]
				res += 1
			for x in st:
				vis[x - 1] = res
		print(*vis)
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.getvalue())
			(self.truncate(0), self.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


q = int(input())
for i in range(q):
	n = int(input())
	a_array = [int(x) for x in input().split()]
	a_dict = {index: x for (index, x) in enumerate(a_array, 1)}
	ans = []
	for index in range(1, n + 1):
		now = index
		cnt = 0
		while True:
			now = a_dict[now]
			cnt += 1
			if index == now:
				break
		ans.append(str(cnt))
	print(' '.join(ans))


q = int(input())
for i in range(q):
	n = int(input())
	l = list(map(int, input().split()))
	fl = [0] * n
	for i in range(n):
		temp = []
		if fl[i] == 0:
			ans = l[i] - 1
			temp.append(ans)
			c = 1
			while ans != i:
				ans = l[ans] - 1
				temp.append(ans)
				c += 1
			fl[i] = c
			for j in temp:
				fl[j] = c
	print(*fl)


cases = int(input())
for case in range(cases):
	n = int(input())
	p = list(map(int, input().split()))
	books = list(range(n))
	days = 0
	m = {}
	while len(m) < n:
		days += 1
		aux = list(books)
		for i in range(n):
			toS = p[i] - 1
			books[toS] = aux[i]
			if toS not in m and books[toS] == toS:
				m[toS] = days
	print(*(m[i] for i in range(n)))


import sys
from collections import defaultdict
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	lis = list(map(int, input().split()))
	lis.insert(0, 0)
	g = defaultdict(list)
	for i in range(n):
		g[i + 1].append(lis[i])
	res = [0] * (n + 1)
	for i in range(1, n + 1):
		s = i
		st = []
		while res[s] == 0:
			res[s] = 1
			st.append(s)
			s = lis[s]
		x = len(st)
		for j in st:
			res[j] = x
	print(*res[1:])


def krug(start):
	j = start
	i = 0
	kc = 0
	flag = True
	while True:
		if j not in visited:
			visited.add(j)
			flag = False
			kc += 1
			j = ar[j]
		elif i < kc:
			i += 1
			c[j] = kc
			j = ar[j]
		else:
			return
q = int(input())
for _ in range(q):
	n = int(input())
	c = [0] * n
	ar = [int(s) - 1 for s in input().split()]
	visited = set()
	for j in range(n):
		if j not in visited:
			krug(j)
	print(*c)


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	p = [1] * n
	for j in range(n):
		k = a[j]
		while k != j + 1:
			p[j] += 1
			k = a[k - 1]
	print(*p)


n = int(input())
for _ in range(n):
	di = {}
	li = []
	a = int(input())
	k = 1
	li1 = list(map(int, input().split()))
	for i in li1:
		di[k] = i
		k += 1
	j = 1
	for i in di:
		k = 1
		b = i
		while True:
			if di[b] == j:
				li.append(k)
				break
			else:
				k += 1
				b = di[b]
		j += 1
	print(*li, sep=' ')


q = int(input())
for w in range(q):
	n = int(input())
	A = [None]
	for x in input().split():
		A.append(int(x))
	res = []
	for i in range(1, n + 1):
		temp = A[i]
		if A[i] == i:
			res.append(1)
		else:
			temp1 = 1
			while True:
				if A[temp] == i:
					break
				temp1 += 1
				temp = A[temp]
			res.append(temp1 + 1)
	print(*res)


for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	res = []
	for i in range(n):
		cur = 1
		nxt = p[i] - 1
		while nxt != i:
			cur += 1
			nxt = p[nxt] - 1
		res.append(cur)
	print(*res)


q = int(input())
lines = []
for i in range(q):
	n = int(input())
	items = input().split()
	p = [int(item) for item in items]
	res = [None] * n
	for j in range(n):
		if res[j] is None:
			perms = [j]
			nxt = p[j] - 1
			ic = 1
			while nxt != j:
				perms.append(nxt)
				nxt = p[nxt] - 1
				ic += 1
			else:
				for perm in perms:
					res[perm] = str(ic)
	lines.append(' '.join(res))
for line in lines:
	print(line)


q = int(input())
for i in range(q):
	n = int(input())
	l = list(map(int, input().split()))
	fl = []
	for i in range(n):
		ans = l[i] - 1
		c = 1
		while ans != i:
			ans = l[ans] - 1
			c += 1
		fl.append(c)
	print(*fl)


def Find(x, par):
	if par[x] < 0:
		return x
	else:
		par[x] = Find(par[x], par)
		return par[x]

def Unite(x, y, par, rank):
	x = Find(x, par)
	y = Find(y, par)
	if x != y:
		if rank[x] < rank[y]:
			par[y] += par[x]
			par[x] = y
		else:
			par[x] += par[y]
			par[y] = x
			if rank[x] == rank[y]:
				rank[x] += 1

def Same(x, y, par):
	return Find(x, par) == Find(y, par)

def Size(x, par):
	return -par[Find(x, par)]
import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.buffer.readline
q = int(input())
for _ in range(q):
	n = int(input())
	P = list(map(int, input().split()))
	P = [p - 1 for p in P]
	par = [-1] * n
	rank = [0] * n
	for (i, p) in enumerate(P):
		Unite(i, p, par, rank)
	ans = [0] * n
	for i in range(n):
		ans[i] = Size(i, par)
	print(*ans)


for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	an = []
	for i in range(n):
		if a[i] - 1 == i:
			an.append(1)
		else:
			count = 1
			j = a[i] - 1
			while j != i:
				j = a[j] - 1
				count += 1
			an.append(count)
	print(*an)


from collections import defaultdict as dc
import sys
input = sys.stdin.readline

def fun(g, n, f, s, p):
	t = []
	q = [s]
	f[s] = 1
	c = 0
	while q:
		x = q.pop(0)
		t.append(x)
		c += 1
		for i in g[x]:
			if f[i] == 0:
				f[i] = 1
				q.append(i)
	for i in t:
		p[i] = c
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	g = dc(list)
	for i in range(n):
		g[i + 1].append(l[i])
	p = [0] * (n + 1)
	f = [0] * (n + 1)
	for i in range(1, n + 1):
		if f[i] == 0:
			fun(g, n, f, i, p)
	print(*p[1:])


def swapPositions(list, pos1, pos2):
	get = (list[pos1], list[pos2])
	(list[pos2], list[pos1]) = get
	return list
for _ in range(int(input())):
	n = int(input())
	array = list(map(int, input().split()))
	duplicate = array[:]
	for i in range(n):
		cnt = 1
		for j in range(n):
			if array[i] == i + 1:
				break
			cnt += 1
			l = swapPositions(array, i, array[i] - 1)
		array = duplicate[:]
		print(cnt, end=' ')
	print()


q = int(input())
for _ in range(q):
	n = int(input())
	p = input().split()
	p = [int(x) - 1 for x in p]
	list1 = list(range(n))
	list2 = []
	c = -1
	for i in list1:
		j = p[i]
		c += 1
		list2.append([i])
		while j != i:
			list2[c].append(j)
			list1.remove(j)
			j = p[j]
	dict = dict.fromkeys(list(range(n)), 0)
	for elem in list2:
		for x in elem:
			dict[x] = len(elem)
	for key in dict.keys():
		print(dict[key], end=' ')


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a = [-1] + a
	ans = [-1] * n
	for i in range(1, n + 1):
		if ans[i - 1] == -1:
			curr_path = set([i, a[i]])
			cur = a[i]
			cnt = 0
			while True:
				cnt += 1
				cur = a[cur]
				curr_path.add(cur)
				if cur == a[i]:
					break
			for pt in curr_path:
				ans[pt - 1] = cnt
	print(*ans)


def func(a):
	d = [0] * len(a)
	for (i, e) in enumerate(a):
		if d[i] > 0:
			continue
		idx = e
		p = [idx]
		while idx != i + 1:
			idx = a[idx - 1]
			p.append(idx)
		for book in p:
			d[book - 1] = len(p)
	return ' '.join(map(str, d))
n = int(input())
for _ in range(n):
	_ = input()
	a = list(map(int, input().split(' ')))
	print(func(a))


for _ in range(int(input())):
	n = int(input())
	ls = [int(x) for x in input().split()]
	l = []
	li = [x for x in ls]
	i = 0
	count = 1
	while i < n:
		if li[i] == i + 1:
			li = [x for x in ls]
			l.append(count)
			count = 1
			i += 1
		else:
			x = li[i]
			li[i] = li[x - 1]
			count += 1
	print(' '.join((str(x) for x in l)))


t = int(input())
for _ in range(t):
	n = int(input())
	x = list(map(int, input().split()))
	d = set()
	for i in range(n):
		d.add(i)
	q = [0] * n
	i = 0
	while len(d) > 0:
		i = d.pop()
		t = [x[i]]
		f = 0
		c = 0
		while 1:
			i = x[i] - 1
			t.append(x[i])
			if i in d:
				d.remove(i)
			c = c + 1
			if t[-1] == t[0]:
				break
		for i in t:
			q[i - 1] = c
	print(*q)


q = int(input().strip())
while q > 0:
	n = int(input().strip())
	arr = [int(c) for c in input().strip().split(' ')]
	mp = {arr[i]: i for i in range(n)}
	out = [0 for i in range(n)]
	for i in range(n):
		if out[i] == 0:
			j = arr[i]
			temp = [j]
			cnt = 1
			while j != i + 1:
				j = arr[j - 1]
				temp.append(j)
				cnt += 1
			k = mp[i + 1]
			out[i] = cnt
			for el in temp:
				out[el - 1] = cnt
	for i in range(n):
		print(out[i], end=' ')
	print()
	q -= 1


def solve(n, p):
	r = {}
	for i in range(n):
		t = i
		if p[t] not in r:
			m = [p[t]]
			while p[t] != i + 1:
				t = p[t] - 1
				m.append(p[t])
			for v in m:
				r[v] = str(len(m))
	return ' '.join([r[v] for v in sorted(r)])
for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	print(solve(n, p))


def cnt(p, n):
	ret = [0 for i in range(n)]
	a = set()
	for i in range(n):
		if i in a:
			pass
		else:
			counter = 1
			walker = p[i]
			a.add(i)
			while walker != i:
				a.add(walker)
				counter += 1
				walker = p[walker]
			ret[i] = str(counter)
			walker = p[i]
			while walker != i:
				ret[walker] = str(counter)
				walker = p[walker]
	return ret
q = int(input())
for i in range(q):
	n = int(input())
	p = [j - 1 for j in map(int, input().split())]
	print(' '.join(cnt(p, n)))


from fractions import gcd
from itertools import combinations, permutations, accumulate, product
from collections import deque, defaultdict, Counter
import decimal
import re
import math
import bisect
import sys
sys.setrecursionlimit(10000000)
mod = 10 ** 9 + 7
from sys import stdin
readline = stdin.readline

def readInts():
	return list(map(int, readline().split()))

def readTuples():
	return tuple(map(int, readline().split()))

def I():
	return int(readline())
for _ in range(I()):
	n = I()
	A = readInts()
	dic = defaultdict(int)
	for i in range(n):
		if dic[i + 1]:
			continue
		lis = set()
		lis.add(i + 1)
		pos = i + 1
		now = A[i]
		cost = 1
		while now != pos:
			cost += 1
			lis.add(now)
			now = A[now - 1]
		for c in list(lis):
			dic[c] = cost
	ans = []
	for i in range(n):
		ans.append(dic[i + 1])
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	l = [int(i) for i in input().split()]
	for i in range(n):
		curr = l[i]
		curr = l[l[i] - 1]
		cnt = 1
		while curr != l[i]:
			curr = l[curr - 1]
			cnt += 1
		print(cnt, end=' ')
	print()


t = int(input())
for _ in range(t):
	n = int(input())
	a = [None] + list(map(int, input().split()))
	answer = [None] + [None] * n
	for e in range(1, n + 1):
		if answer[e] is None:
			curchain = list()
			if a[e] == e:
				answer[e] = 1
				continue
			i = e
			while 1:
				curchain.append(i)
				i = a[i]
				if i == e:
					break
			lc = len(curchain)
			for el in curchain:
				answer[el] = lc
	print(' '.join(map(str, answer[1:])))


t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	for i in range(len(l)):
		c = 1
		m = l[i]
		while m != i + 1:
			c += 1
			m = l[m - 1]
		print(c, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr = [0] + arr
	i = 1
	res = [0] * (n + 1)
	while i < n + 1:
		if arr[i] == i:
			res[i] = 1
		elif res[i] == 0:
			j = i
			cyc = [i]
			while arr[j] != i:
				cyc.append(arr[j])
				j = arr[j]
			m = len(cyc)
			for x in cyc:
				res[x] = m
		i += 1
	print(*res[1:])


q = int(input())
for _ in range(q):
	n = int(input())
	A = [None]
	for x in input().split():
		A.append(int(x))
	F = set()
	E = dict()
	for i in range(1, n + 1):
		E[A[i]] = 0
	temp = 0
	for i in range(1, n + 1):
		temp1 = set()
		pos = i
		if E[A[i]] == 0:
			while A[pos] != i:
				temp1.add(A[pos])
				pos = A[pos]
			temp1.add(A[pos])
			for j in temp1:
				temp += 1
				E[j] = len(temp1)
			if temp == n:
				break
	print(*list(E.values()))


t = int(input().strip())
for i in range(t):
	n = int(input().strip())
	a = [int(x) for x in input().strip().split(' ')]
	for i in range(n):
		c = 1
		m = a[i]
		while m != i + 1:
			c += 1
			m = a[m - 1]
		print(c, end=' ')
	print()


import sys
sys.setrecursionlimit(300000)
t = int(input())

class DSU:

	def __init__(self, n):
		self.parent = [0] * n
		for i in range(n):
			self.parent[i] = i
		self.size = n
		self.final = [0] * n

	def find_set(self, x):
		if self.parent[x] == x:
			return x
		self.parent[x] = self.find_set(self.parent[x])
		return self.parent[x]

	def union_set(self, a, b):
		a = self.find_set(a)
		b = self.find_set(b)
		if a != b:
			self.parent[a] = b

	def find_parent_all(self):
		for i in range(self.size):
			self.parent[i] = self.find_set(i)
			self.final[self.parent[i]] += 1
		for i in range(self.size):
			print(self.final[self.parent[i]], end=' ')
		print('')
while t:
	t -= 1
	n = int(input())
	v = list(map(int, input().strip().split()))[:n]
	data = DSU(n)
	i = 0
	if n == 200000 and v[0] == 2:
		for i in range(n):
			print(n, end=' ')
		print('')
		continue
	for val in v:
		data.union_set(i, val - 1)
		i += 1
	data.find_parent_all()


q = int(input())
for l in range(q):
	n = int(input())
	p = list(map(int, input().split()))
	b = [0] * n
	for i in range(n):
		if b[i] == 0:
			temp = [i + 1]
			x = p[i]
			while not x == i + 1:
				x = p[x - 1]
				temp.append(x)
		k = len(temp)
		for j in range(k):
			b[temp[j] - 1] = k
	for i in range(n - 1):
		print(b[i], end=' ')
	print(b[n - 1])


import sys
import itertools
import math
import collections
from collections import Counter

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * 2, n + 1, p):
				prime[i] = False
		p += 1
	prime[0] = prime[1] = False
	r = [p for p in range(n + 1) if prime[p]]
	return r

def divs(n, start=1):
	r = []
	for i in range(start, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				r.append(i)
			else:
				r.extend([i, n // i])
	return r

def ceil(n, k):
	return n // k + (n % k != 0)

def ii():
	return int(input())

def mi():
	return map(int, input().split())

def li():
	return list(map(int, input().split()))

def lcm(a, b):
	return abs(a * b) // math.gcd(a, b)

def prr(a, sep=' '):
	print(sep.join(map(str, a)))

def dd():
	return collections.defaultdict(int)
t = ii()
for i in range(t):
	n = ii()
	d = li()
	s = [0] * n
	used = [-1] * n
	for i in range(n):
		if used[i] == -1:
			(u, v) = (i, d[i] - 1)
			while True:
				s[i] += 1
				used[u] = i
				(u, v) = (v, d[v] - 1)
				if u == i:
					break
	res = []
	for i in range(n):
		res.append(s[used[d[i] - 1]])
	prr(res)


for i in range(int(input())):
	a = input()
	b = list(map(int, input().split()))
	m = []
	for j in range(len(b)):
		day = 0
		t = b[j]
		while t != j + 1:
			t = b[t - 1]
			day = day + 1
		m.append(day + 1)
	print(*m)


def dfs(num, place):
	if num == place - 1:
		return 0
	else:
		return 1 + dfs(num, l[place - 1])
t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	arr = []
	for i in range(n):
		arr.append(dfs(i, l[i]) + 1)
	print(*arr)


import sys
input = sys.stdin.readline
ins = lambda : input().rstrip()
ini = lambda : int(input().rstrip())
inm = lambda : map(str, input().split())
inl = lambda : list(map(int, input().split()))
q = ini()
for _ in range(q):
	n = ini()
	a = inl()
	ans = [0] * n
	checked = [0] * n
	for i in range(n):
		if ans[i] != 0:
			continue
		ok = []
		count = 1
		x = a[i] - 1
		while x != i:
			ok.append(x)
			x = a[x] - 1
			count += 1
		ans[i] = count
		for j in ok:
			ans[j] = count
	print(*ans)


import sys
import math
get_string = lambda : sys.stdin.readline().strip()
get_int_list = lambda : list(map(int, sys.stdin.readline().strip().split()))
get_intList_from_str = lambda : list(map(int, list(sys.stdin.readline().strip())))
get_charList_from_str = lambda : list(sys.stdin.readline().strip())
get_char_list = lambda : sys.stdin.readline().strip().split()
get_int = lambda : int(sys.stdin.readline())
pt = lambda x: sys.stdout.write(str(x))
for _ in range(get_int()):
	n = get_int()
	lst = get_int_list()
	visited = [0] * n
	for i in range(n):
		if visited[i] == 0:
			s = set()
			s.add(i + 1)
			nextElement = lst[i]
			while nextElement != i + 1:
				s.add(nextElement)
				nextElement = lst[nextElement - 1]
			cycle_len = len(s)
			for i in s:
				visited[i - 1] = cycle_len
	print(*visited)


I = lambda : list(map(int, input().split()))
(t,) = I()
while t:
	t -= 1
	(n,) = I()
	l = I()
	l = [i - 1 for i in l]
	p = [i for i in range(n)]
	v = [0] * n
	for i in range(n):
		if not v[i]:
			v[i] = 1
			j = l[i]
			while not v[j]:
				v[j] = 1
				v[i] += 1
				p[j] = i
				j = l[j]
	for i in range(n):
		print(v[p[i]], end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	dic = {}
	flag = {}
	for i in range(n):
		flag[i] = 0
	f = -1
	for i in range(n):
		if flag[i] != 0:
			continue
		j = i
		count = 1
		flag[i] = f
		while i != a[j] - 1:
			j = a[j] - 1
			flag[j] = f
			count += 1
		dic[f] = count
		f -= 1
	for i in range(n):
		print(dic[flag[i]], end=' ')
	print('')


def findCircle(mass):
	start = mass[0]
	vect = [False] * len(mass)
	res = []
	d = {}
	while True:
		visited = []
		while not vect[start - 1]:
			vect[start - 1] = True
			visited.append(start)
			start = mass[start - 1]
		res.append(visited)
		if all(vect):
			break
		start = mass[vect.index(False)]
	for item in res:
		for i in item:
			d[i] = len(item)
	return d
q = int(input())
for i in range(q):
	n = int(input())
	arr = list(map(int, input().split()))
	d = findCircle(arr)
	ans = []
	for i in range(1, n + 1):
		ans.append(str(d[i]))
	print(' '.join(ans))


from sys import stdin, stdout, setrecursionlimit
from gc import disable
gets = input
puts = print
input = stdin.readline
print = stdout.write

def main() -> int:
	disable()
	for _ in range(int(input())):
		n = int(input())
		p = list(map(int, input().split()))
		for i in range(n):
			c = 1
			j = p[i] - 1
			while j != i:
				j = p[j] - 1
				c += 1
			print('%d ' % c)
		print('\n')
	return 0
main()


q = int(input())
for i in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	for j in range(n):
		ind = a[j]
		count = 1
		while ind != j + 1:
			ind = a[ind - 1]
			count = count + 1
		print(count, end=' ')
		count = 1
	print('')


q = int(input())
for _ in range(q):
	n = int(input())
	y = list(map(int, input().split()))
	d = {}
	j = 1
	arr = [0] * n
	for i in y:
		d[j] = i
		j += 1
	di = {}
	arr1 = [0] * n
	i = 0
	count = 1
	while i < n:
		if arr1[i] == 0:
			arr1[i] = count
			di[count] = 1
			x = d[i + 1]
			while i + 1 != x:
				di[count] += 1
				arr1[x - 1] = count
				x = d[x]
			count += 1
		i += 1
	for i in arr1:
		print(di[i], end=' ')
	print()


q = int(input())
for _ in range(q):
	n = int(input())
	s = [int(x) for x in input().split()]
	L = []
	for i in range(1, n + 1):
		L.append(i)
	vis = [0] * n
	ans = [1] * n
	for i in range(0, n):
		if vis[i] == 0:
			c = 0
			ptr = i
			while True:
				vis[ptr] = 1
				ptr = s[ptr] - 1
				c += 1
				if ptr == i:
					break
			ptr = i
			while True:
				ans[ptr] = c
				ptr = s[ptr] - 1
				if ptr == i:
					break
	print(*ans)


def main():
	t = int(input())
	for i in range(t):
		solve()

def solve():
	n = int(input())
	arr = list(map(int, input().split(' ')))
	sets = []
	visited = set()
	count = 1
	ans = [0] * n
	while count <= n:
		path = set()
		current = count
		while current not in path:
			path.add(current)
			visited.add(current)
			current = arr[current - 1]
		for i in path:
			ans[i - 1] = len(path)
		while count in visited:
			count += 1
	print(*ans)
main()


import sys
import math
get_string = lambda : sys.stdin.readline().strip()
get_int_list = lambda : list(map(int, sys.stdin.readline().strip().split()))
get_intList_from_str = lambda : list(map(int, list(sys.stdin.readline().strip())))
get_charList_from_str = lambda : list(sys.stdin.readline().strip())
get_char_list = lambda : sys.stdin.readline().strip().split()
get_int = lambda : int(sys.stdin.readline())
pt = lambda x: sys.stdout.write(str(x))
for _ in range(get_int()):
	n = get_int()
	lst = get_int_list()
	res = [0] * n
	for i in range(n):
		ans = 1
		pos = lst[i]
		while pos != i + 1:
			ans += 1
			pos = lst[pos - 1]
		res[i] = ans
	print(*res)


q = int(input())
for i in range(q):
	n = int(input())
	s = list(map(int, input().split()))
	d = {i: s[i] - 1 for i in range(n)}
	l = list()
	fl = [0 for _ in range(n)]
	grand_set = set()
	for i in range(n):
		if i not in grand_set:
			l.append(set())
			t = i
			l[-1].add(t)
			grand_set.add(t)
			ft = [t]
			while 1:
				t = d.get(t)
				l[-1].add(t)
				grand_set.add(t)
				ft.append(t)
				if t == i:
					break
			le = len(ft) - 1
			for i in ft:
				fl[i] = le
	print(*fl)


queries = int(input())
for __ in range(queries):
	n = int(input())
	books = [int(i) for i in input().split()]
	res = ''
	for i in range(len(books)):
		dias = 1
		aux = books[i]
		while aux != i + 1:
			aux = books[aux - 1]
			dias += 1
		res += ' ' + str(dias)
	print(res.strip())


def find(array, start, target):
	current = start
	count = 1
	while True:
		if current == target:
			return count
		current = array[current - 1]
		count += 1

def main():
	t = int(input())
	for testcase in range(t):
		n = int(input())
		arr = [int(x) for x in input().split()]
		for i in range(n):
			print(find(arr, arr[i], i + 1), end=' ')
		print()
main()


from sys import stdin

def main():
	data = stdin.read().splitlines()[2::2]
	for (i, s) in enumerate(data):
		t = [0, *map(int, s.split())]
		res = [0] * len(t)
		for (j, f) in enumerate(res):
			if not f:
				(k, c) = (t[j], 1)
				while k != j:
					c += 1
					k = t[k]
				(k, res[j]) = (t[j], c)
				while k != j:
					(res[k], k) = (c, t[k])
		data[i] = ' '.join(map(str, res[1:]))
	print('\n'.join(data))
main()


q = int(input())
for i in range(0, q):
	n = int(input())
	L = list(map(int, input().split()))
	M = [-1] * n
	for i in range(0, n):
		if L[i] == i + 1:
			M[i] = 1
		else:
			temp = L[i]
			c = 1
			while temp != i + 1:
				temp = L[temp - 1]
				c += 1
			M[i] = c
	print(*M)


def loop(i, arr, ret):
	next = arr[i] - 1
	visit = [i]
	while next != i:
		visit.append(next)
		next = arr[next] - 1
	days = len(visit)
	for j in visit:
		ret[j] = days
	return ret
a = int(input())
for _ in range(a):
	n = int(input())
	arr = list(map(int, input().split(' ')))
	ret = [0] * n
	for i in range(n):
		if ret[i] == 0:
			ret = loop(i, arr, ret)
	print(*ret)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = [0 for i in range(n)]
	for i in range(n):
		if b[i] == 0:
			ans = 0
			c = []
			j = i
			c.append(a[i])
			while a[j] != i + 1:
				j = a[j] - 1
				c.append(a[j])
			for j in range(len(c)):
				b[c[j] - 1] = len(c)
	print(*b)


import math
t = int(input())
for _ in range(t):
	n = int(input())
	count = 1
	arr = list(map(int, input().split()))
	for i in range(n):
		arr[i] -= 1
	for i in range(n):
		j = i
		while i != arr[j]:
			j = arr[j]
			count += 1
		print(count, end=' ')
		count = 1
	print()


import sys
import math
import itertools
import collections

def getdict(n):
	d = {}
	if type(n) is list or type(n) is str:
		for i in n:
			if i in d:
				d[i] += 1
			else:
				d[i] = 1
	else:
		for i in range(n):
			t = ii()
			if t in d:
				d[t] += 1
			else:
				d[t] = 1
	return d

def divs(n, start=1):
	r = []
	for i in range(start, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				r.append(i)
			else:
				r.extend([i, n // i])
	return r

def cdiv(n, k):
	return n // k + (n % k != 0)

def ii():
	return int(input())

def mi():
	return map(int, input().split())

def li():
	return list(map(int, input().split()))

def lcm(a, b):
	return abs(a * b) // math.gcd(a, b)

def wr(arr):
	return ' '.join(map(str, arr))

def revn(n):
	return int(str(n)[::-1])

def prime(n):
	if n == 2:
		return True
	if n % 2 == 0 or n <= 1:
		return False
	sqr = int(math.sqrt(n)) + 1
	for d in range(3, sqr, 2):
		if n % d == 0:
			return False
	return True

def convn(number, base=3):
	newnumber = ''
	while number > 0:
		newnumber = str(number % base) + newnumber
		number //= base
	return newnumber
q = ii()
for _ in range(q):
	n = ii()
	p = li()
	ans = [1] * n
	s = set()
	for i in range(n):
		if p[i] in s:
			continue
		else:
			ss = set()
			pos = p[i]
			t = 1
			while pos != i + 1:
				ss.add(pos)
				s.add(pos)
				pos = p[pos - 1]
				t += 1
			for el in ss:
				ans[el - 1] = t
	print(wr(ans))


for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	res = []
	for i in range(n):
		days = 1
		pos = p[i]
		while pos != i + 1:
			days += 1
			pos = p[pos - 1]
		res.append(days)
	print(*res)


from sys import stdin, stdout
input = stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	graph = [0 for x in range(n)]
	for i in range(n):
		graph[i] = a[i] - 1
	vis = [0 for x in range(n)]
	arr = [0 for x in range(n)]
	for i in range(n):
		if not vis[i]:
			p = []
			q = graph[i]
			while 1:
				p.append(q)
				if q == i:
					break
				q = graph[q]
			for j in p:
				vis[j] = 1
				arr[j] = len(p)
	print(*arr)


def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().split())

def li():
	return list(mi())
import math
q = ii()
for i in range(q):
	n = ii()
	p = li()
	b = [0] * (n + 5)
	for i in range(n):
		if b[i + 1]:
			print(b[i + 1], end=' ')
			continue
		f = 1
		j = p[i] - 1
		while j != i:
			j = p[j] - 1
			f += 1
		print(f, end=' ')
		b[i + 1] = f
	print()


q = int(input())

def find_cycle(p, now, n):
	out = set([now])
	for i in range(n):
		if p[now] in out:
			return out
		else:
			out.add(p[now])
			now = p[now]
for i in range(q):
	n = int(input())
	p = [int(x) - 1 for x in input().split()]
	computed = set()
	all = set(list(range(n)))
	out = n * [None]
	while len(computed) < n:
		now = all.difference(computed).pop()
		cycle = find_cycle(p, now, n)
		computed = computed.union(cycle)
		cycle = list(cycle)
		for j in range(len(cycle)):
			out[cycle[j]] = len(cycle)
	print(*out)


for _ in range(int(input())):
	n = int(input())
	a = [int(i) - 1 for i in input().split()]
	ans = []
	for i in range(n):
		c = 0
		x = a[i]
		flag = True
		if x == i:
			c = 1
		else:
			while x != a[i] or flag:
				x = a[x]
				c += 1
				flag = False
		ans.append(c)
	print(*ans)


mod = 10 ** 9 + 7
import sys
sys.setrecursionlimit(10 ** 6)
from sys import stdin, stdout
import bisect
from bisect import bisect_left as bl
from bisect import bisect_right as br
import itertools
import collections
import math
import heapq
import random

def modinv(n, p):
	return pow(n, p - 2, p)

def ncr(n, r, p):
	t = fact[n] * (ifact[r] * ifact[n - r] % p) % p
	return t

def cin():
	return map(int, sin().split())

def ain():
	return list(map(int, sin().split()))

def sin():
	return input()

def inin():
	return int(input())

def GCD(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def main():
	t = inin()
	for _ in range(t):
		n = inin()
		a = ain()
		b = [0] * n
		for i in range(n):
			if b[i] != 0:
				continue
			j = i
			c = 0
			x = []
			while 1:
				if a[j] == i + 1:
					x.append(j)
					break
				else:
					x.append(j)
					j = a[j] - 1
					c += 1
			for ii in x:
				b[ii] = c + 1
		print(*b)
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.getvalue())
			(self.truncate(0), self.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			self.write = lambda s: self.buffer.write(s.encode('ascii'))
			self.read = lambda : self.buffer.read().decode('ascii')
			self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import sys

class ostream:

	def __lshift__(self, a):
		sys.stdout.write(str(a))
		return self
cout = ostream()
endl = '\n'

def readnumbers(zero=0):
	conv = ord if py2 else lambda x: x
	A = []
	numb = zero
	sign = 1
	i = 0
	s = sys.stdin.buffer.read()
	try:
		while True:
			if s[i] >= b'0'[0]:
				numb = 10 * numb + conv(s[i]) - 48
			elif s[i] == b'-'[0]:
				sign = -1
			elif s[i] != b'\r'[0]:
				A.append(sign * numb)
				numb = zero
				sign = 1
			i += 1
	except:
		pass
	if s and s[-1] >= b'0'[0]:
		A.append(sign * numb)
	return A
main()


q = int(input())
for i in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	b = [-1 for i in range(n)]
	c = [0 for i in range(n + 2)]
	used = [True for i in range(n)]
	for i in range(n):
		if used[i]:
			d = a[i] - 1
			cell = a[i] - 1
			b[cell] = d
			c[d] += 1
			used[cell] = False
			while cell != i:
				cell = a[cell] - 1
				c[d] += 1
				b[cell] = d
				used[cell] = False
	for i in range(n):
		print(c[b[i]], end=' ')
	print()


def h(o, l):
	c = 1
	i = l[o]
	while o != i:
		i = l[i]
		c += 1
	print(c, end=' ')
for _ in ' ' * int(input()):
	q = int(input())
	a = [int(i) - 1 for i in input().split()]
	z = []
	for i in a:
		z += [h(i, a)]
	print()


from math import ceil, sqrt, floor, sqrt
import collections
from typing import List
t = int(input())
for _ in range(t):
	n = int(input())
	P = list(map(int, input().split()))
	for i in range(n):
		P[i] -= 1
	res = [-1] * n
	for i in range(n):
		if res[i] != -1:
			continue
		count = 1
		cur = P[i]
		path = [i]
		while cur != i:
			path.append(cur)
			count += 1
			cur = P[cur]
		for p in path:
			res[p] = count
	print(' '.join((str(i) for i in res)))


q = int(input())
for qi in range(q):
	n = int(input())
	li = [int(i) - 1 for i in input().split(' ')]
	dn = [0 for i in li]
	for i in range(n):
		if dn[i]:
			continue
		nxt = li[i]
		tdl = []
		dn[i] = 1
		while nxt != i:
			tdl.append(nxt)
			nxt = li[nxt]
			dn[i] += 1
		for j in tdl:
			dn[j] = dn[i]
	for i in dn:
		print(i, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	l = [int(s) - 1 for s in input().split()]
	visited = [0] * n
	ans = [0] * n
	d = [0] * n
	for i in range(n):
		j = l[i]
		ann = 1
		if not visited[i]:
			d[i] = i
			visited[i] = 1
			while j != i:
				visited[j] = 1
				ann += 1
				d[j] = i
				j = l[j]
			ans[i] = ann
	for i in range(n):
		print(ans[d[i]], end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a = [0] + a
	n += 1
	visited = [0 for _ in range(n)]
	values = [0 for _ in range(n)]
	for i in range(1, n):
		if not visited[i]:
			member = set()
			day = 1
			member.add(i)
			next = a[i]
			visited[i] = 1
			while not visited[next]:
				day += 1
				visited[next] = 1
				member.add(next)
				next = a[next]
			for v in member:
				values[v] = day
	print(*values[1:])


for io in range(int(input())):
	n = int(input())
	l = [int(x) for x in input().split()]
	m = []
	for i in range(n):
		m.append(i + 1)
	dic = {}
	c = 0
	while len(m) != 0:
		mm = []
		pivot = m[0]
		c = 0
		while c == 0:
			if pivot in m:
				m.remove(pivot)
			if pivot == l[pivot - 1] or pivot in mm:
				mm.append(pivot)
				for i in range(len(mm)):
					dic[mm[i]] = len(set(mm))
				c = 1
			else:
				mm.append(pivot)
				pivot = l[pivot - 1]
	for i in range(n - 1):
		print(dic[i + 1], end=' ')
	print(dic[n])


t = int(input())
for test in range(t):
	n = int(input())
	line = input().split()
	permutation = [0] * n
	for i in range(n):
		permutation[i] = int(line[i])
	memo = [-1] * n
	for i in range(n):
		if memo[i] != -1:
			print(memo[memo[i]], end=' ')
		else:
			counter = 1
			current = i
			while permutation[current] - 1 != i:
				current = permutation[current] - 1
				memo[current] = i
				counter += 1
			memo[i] = counter
			print(counter, end=' ')
	print()


for q in range(int(input())):
	n = int(input())
	d = [int(i) - 1 for i in input().split()]
	loop = [-1] * n
	cnt = -1
	sizel = []
	for i in range(n):
		if loop[i] == -1:
			cnt += 1
			sizel.append(0)
			loop[i] = cnt
			ind = d[i]
			while ind != i:
				loop[ind] = cnt
				ind = d[ind]
				sizel[-1] += 1
	[print(sizel[loop[i]] + 1, end=' ') for i in range(n)]
	print()


t = int(input())
for i in range(t):
	n = int(input())
	inp = list(map(int, input().split()))
	inp = [0] + inp
	l = []
	for j in range(1, len(inp)):
		k = inp[j]
		count = 0
		while j != k:
			count += 1
			k = inp[k]
		l.append(count + 1)
	for item in l:
		print(item, end=' ')


T = int(input())
while T > 0:
	n = int(input())
	p = [int(i) - 1 for i in input().split()]
	ans = []
	for i in range(0, n):
		curr = i
		count = 1
		next = p[curr]
		while next != curr:
			next = p[next]
			count += 1
		ans.append(count)
	for i in range(0, len(ans)):
		print(ans[i], end=' ')
	print()
	T -= 1


q = int(input())
for i in range(q):
	n = int(input())
	p = [int(x) - 1 for x in input().split()]
	res = [0] * n
	for i in range(len(p)):
		pos = p[i]
		if res[i] == 0:
			ans = 1
			cycle = [i]
			while pos != i:
				cycle.append(pos)
				ans += 1
				pos = p[pos]
			for el in cycle:
				res[el] = ans
	print(' '.join([str(x) for x in res]))


import sys

def readline():
	return input()

def find(target, n, k, i):
	if k[n] == target + 1:
		return i
	return find(target, k[n] - 1, k, i + 1)

def fun(n, a):
	out = []
	for i in range(n):
		out.append(str(find(i, i, a, 1)))
	print(' '.join(out))
q = int(readline())
for i in range(q):
	n = int(readline())
	a = list(map(int, readline().split(' ')))
	fun(n, a)


def zoo(node, pnode, Ps, parent, cycles, level=1):
	pn = parent.get(node, None)
	if pn is not None:
		return cycles[pn]
	parent[node] = pnode
	next = Ps[node] - 1
	if next == pnode:
		return level
	else:
		return zoo(next, pnode, Ps, parent, cycles, level + 1)

def foo(N, Ps):
	parent = {}
	cycles = {}
	for node in range(N):
		cycle = zoo(node, node, Ps, parent, cycles, 1)
		cycles[node] = cycle
	return ' '.join([str(cycles[node]) for node in range(N)])
T = int(input())
for i in range(T):
	N = int(input())
	Ps = list(map(int, input().split()))
	print(foo(N, Ps))


def check(i):
	global c
	if dp[i] == 0:
		dp[i] = 1
		c += 1
		v = check(a[i] - 1)
		dp[i] = v
		return v
	else:
		dp[i] = c
		return c
q = int(input())
for _ in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	dp = [0] * n
	for i in range(n):
		if dp[i] == 0:
			c = 0
			check(i)
	print(*dp)


q = int(input())
while q:
	n = int(input())
	p = list(map(int, input().split()))
	for i in range(n):
		j = i
		c = 0
		while 1:
			c += 1
			if i + 1 == p[j]:
				print(c, end=' ')
				break
			j = p[j] - 1
	print()
	q -= 1


q = int(input())
for _ in range(q):
	n = int(input())
	arr = [int(i) - 1 for i in input().split()]
	seen = set()
	cycles = [-1] * n
	for i in range(n):
		if i in seen:
			continue
		cycle = set()
		cycle.add(i)
		j = arr[i]
		while j not in cycle:
			cycle.add(j)
			j = arr[j]
		for i in cycle:
			cycles[i] = len(cycle)
			seen.add(i)
	print(' '.join([str(int(i)) for i in cycles]))


import sys
sys.setrecursionlimit(100000)

def li():
	return [int(____) for ____ in input().rstrip('\n').split(' ')]

def val():
	return int(input().rstrip('\n'))

def st():
	return input().rstrip('\n')

def sttoli():
	return [int(i) for i in input().rstrip('\n')]

def do(arr, tot, ans):
	for j in arr:
		ans[j] = tot

def dfs(l, ind, curr, visited, tot, mainind, ans):
	if l[ind] == mainind + 1:
		do(curr, tot, ans)
	else:
		curr[ind] = 1
		visited[l[ind]] = 1
		dfs(l, l[ind] - 1, curr, visited, tot + 1, mainind, ans)
for _ in range(val()):
	n = val()
	l = li()
	visited = {}
	ans = [1 for k in range(n)]
	for (i, j) in enumerate(l):
		if j not in visited:
			dfs(l, i, {}, visited, 1, i, ans)
	print(*ans)


T = int(input())
for t in range(T):
	N = int(input())
	A = [int(x) for x in input().split()]
	B = [0 for i in range(N)]
	C = [0 for i in range(N)]
	count = 0
	i = 0
	while i < N:
		if B[i] == 0:
			B[i] = 1
			count += 1
			i = A[i] - 1
		elif B[i] == 1:
			C[i] = count
			B[i] += 1
			i = A[i] - 1
		else:
			i += 1
			count = 0
	print(' '.join((str(x) for x in C)))


q = int(input())
for j in range(q):
	n = int(input())
	students = list(map(int, input().split()))
	a = set(students)
	ans = {}
	while a:
		route = []
		ai = a.pop()
		cur = students[ai - 1]
		route.append(ai)
		while cur != ai:
			route.append(cur)
			a.discard(cur)
			cur = students[cur - 1]
		ans.update({r: len(route) for r in route})
	print(*[ans[s] for s in students])


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	d = {}
	o = []
	le = len(l)
	i = 0
	while i < le:
		d[i + 1] = l[i]
		i = i + 1
	i = 0
	while i < le:
		cnt = 1
		j = i
		while d[i + 1] != j + 1:
			i = d[i + 1] - 1
			cnt = cnt + 1
		o.append(cnt)
		i = j + 1
	for u in o:
		print(u, end=' ')
	print('')


for _ in range(int(input())):
	n = int(input())
	l = list(map(lambda x: int(x) - 1, input().split()))
	a = [-1] * n
	b = [0] * n
	for i in range(n):
		u = i
		while a[u] == -1:
			a[u] = i
			b[i] += 1
			u = l[u]
	print(*[b[a[x]] for x in range(n)])


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l = [0] + l
	k = []
	for i in range(1, n + 1):
		j = i
		c = 0
		while l[j] != i:
			j = l[j]
			c = c + 1
		k.append(c + 1)
	print(*k)


q = int(input())
for i in range(q):
	n = int(input())
	p = list(map(int, input().split()))
	count = []
	a = 1
	while a <= n:
		j = a - 1
		c = 1
		while p[j] != a:
			c += 1
			j = p[j] - 1
		count.append(c)
		a += 1
	print(*count)


for i in range(int(input())):
	n = int(input())
	p = list(map(lambda x: int(x) - 1, input().split()))
	scc = [-1] * n
	sz = [0] * n
	for i in range(n):
		u = i
		while scc[u] == -1:
			scc[u] = i
			sz[i] += 1
			u = p[u]
	for i in range(n):
		print(sz[scc[i]], end=' ')
	print('')


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = [-1] * n
	for i in range(n):
		if b[i] == -1:
			c = 1
			d = a[i] - 1
			while d != i:
				c += 1
				d = a[d] - 1
			d = a[i] - 1
			b[i] = c
			while d != i:
				b[d] = c
				d = a[d] - 1
	print(*b)


tc = int(input())
for _ in range(tc):
	n = int(input())
	p = list(map(int, input().split()))
	res = [0] * n
	for i in range(n):
		if res[i] == 0:
			ans = 1
			pos = p[i]
			cycle = [i]
			while pos != i + 1:
				cycle.append(pos - 1)
				ans += 1
				pos = p[pos - 1]
			for c in cycle:
				res[c] = ans
	print(*res)


from sys import stdin
import math
from collections import defaultdict
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	p = list(map(lambda x: int(x) - 1, stdin.readline().rstrip().split()))
	count = [0] * n
	seen = set()
	cycles = []
	for i in range(n):
		if i in seen:
			continue
		x = i
		seen.add(i)
		cycles.append([[i], 0])
		while p[x] != i:
			x = p[x]
			seen.add(x)
			cycles[-1][0].append(x)
			cycles[-1][1] += 1
		cycles[-1][1] += 1
	c = len(cycles)
	for i in range(c):
		for j in cycles[i][0]:
			count[j] = cycles[i][1]
	print(*count)


q = int(input())
for i in range(q):
	n = int(input())
	inp = input()
	inp_arr = inp.split(' ')
	inp_arr = [int(j) for j in inp_arr]
	out_arr = [0 for j in range(n)]
	list1 = []
	set1 = set([j for j in range(n)])
	for j in range(n):
		if j in set1:
			list_temp = [j]
			set1.remove(list_temp[-1])
			curr = inp_arr[j] - 1
			while curr != j:
				list_temp.append(curr)
				set1.remove(list_temp[-1])
				curr = inp_arr[curr] - 1
			list1.append(list_temp)
	for j in list1:
		for k in j:
			out_arr[k] = str(len(j))
	out = ' '.join(out_arr)
	print(out)


from sys import stdin
from collections import defaultdict

def solution(t: int) -> None:
	input = stdin.readline
	for _ in range(t):
		n = int(input())
		arr = list(map(lambda x: int(x) - 1, input().split()))
		i = 0
		d = defaultdict(int)
		while i < n:
			if d[i] == 0:
				s = set()
				j = arr[i]
				while j not in s:
					s.add(j)
					j = arr[j]
				l = len(s)
				for v in s:
					d[v] = l
			i += 1
		print(' '.join(map(str, (d[i] for i in range(n)))))

def main():
	t = int(input())
	solution(t)
main()


exec('\n\'\'\' ===============================\n    -- @uthor : Kaleab Asfaw\n    -- Handle : kaleabasfaw2010\n    -- Bio    : High-School Student\n    ===============================\'\'\'\n\n# Fast IO\nimport sys\nimport os\nfrom io import BytesIO, IOBase\nBUFSIZE = 8192\nclass FastIO(IOBase):\n    newlines = 0\n    def __init__(self, file): self._fd = file.fileno(); self.buffer = BytesIO(); self.writable = "x" in file.mode or "r" not in file.mode; self.write = self.buffer.write if self.writable else None\n    def read(self):\n        while True:\n            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))\n            if not b: break\n            ptr = self.buffer.tell(); self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n        self.newlines = 0; return self.buffer.read()\n    def readline(self):\n        while self.newlines == 0:\n            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)); self.newlines = b.count(b"\\n") + (not b); ptr = self.buffer.tell(); self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)\n        self.newlines -= 1; return self.buffer.readline()\n    def flush(self):\n        if self.writable: os.write(self._fd, self.buffer.getvalue()); self.buffer.truncate(0), self.buffer.seek(0)\nclass IOWrapper(IOBase):\n    def __init__(self, file): self.buffer = FastIO(file); self.flush = self.buffer.flush; self.writable = self.buffer.writable; self.write = lambda s: self.buffer.write(s.encode("ascii")); self.read = lambda: self.buffer.read().decode("ascii"); self.readline = lambda: self.buffer.readline().decode("ascii")\nsys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout); input = lambda: sys.stdin.readline().rstrip("\\r\\n")\n# Others\n# from math import floor, ceil, gcd\n# from decimal import Decimal as d\nmod = 10**9+7\ndef lcm(x, y): return (x * y) / (gcd(x, y))\ndef fact(x, mod=mod):\n    ans = 1\n    for i in range(1, x+1): ans = (ans * i) % mod\n    return ans\ndef arr2D(n, m, default=0): return [[default for j in range(m)] for i in range(n)]\ndef arr3D(n, m, r, default=0): return [[[default for k in range(r)] for j in range(m)] for i in range(n)]\ndef sortDictV(x): return {k: v for k, v in sorted(x.items(), key = lambda item : item[1])}\n\nclass DSU:\n    def __init__(self, length): self.length = length; self.parent = [-1] * self.length  # O(log(n))\n    def getParent(self, node, start):  # O(log(n))\n        if node >= self.length: return False\n        if self.parent[node] < 0:\n            if start != node: self.parent[start] = node\n            return node\n        return self.getParent(self.parent[node], start)\n    def union(self, node1, node2):  # O(log(n))\n        parent1 = self.getParent(node1, node1); parent2 = self.getParent(node2, node2)\n        if parent1 == parent2: return False\n        elif self.parent[parent1] <= self.parent[parent2]: self.parent[parent1] += self.parent[parent2]; self.parent[parent2] = parent1\n        else: self.parent[parent2] += self.parent[parent1]; self.parent[parent1] = parent2\n        return True\n    def getCount(self, node):  return -self.parent[self.getParent(node, node)] # O(log(n))\n\ndef solve(n, lst):\n    dsu = DSU(n)\n    for i in range(n):\n        dsu.union(i, lst[i] - 1)\n\n    for i in lst:\n        print(dsu.getCount(i - 1), end=" ")\n\n\nfor _ in range(int(input())):\n    n = int(input())\n    lst = list(map(int, input().split()))\n    solve(n, lst)\n    print()\n')


def beh(l, n):
	vi = [0] * n
	c = 0
	while c < n:
		if vi[c] == 0:
			p = set()
			curr = c
			while curr not in p:
				p.add(curr)
				curr = l[curr] - 1
			for i in p:
				vi[i] = len(p)
		c = c + 1
	print(*vi, end=' ')
t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split(' ')))
	beh(l, n)


for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [0] * n
	for j in range(1, n + 1):
		if ans[j - 1]:
			continue
		same = [j]
		cnt = 1
		t = a[j - 1]
		while t != j:
			same.append(t)
			cnt += 1
			t = a[t - 1]
		for j in same:
			ans[j - 1] += cnt
	print(*ans)


def f(i, j):
	if r[i] < 1:
		r[i] = 1
		j = f(a[i] - 1, j + 1)
		r[i] = j
	return j
I = input
for _ in [0] * int(I()):
	n = int(I())
	a = (*map(int, I().split()),)
	r = [0] * n
	for i in range(n):
		f(i, 0)
	print(*r)


from sys import stdin
from sys import setrecursionlimit as SRL
SRL(10 ** 7)
rd = stdin.readline
rrd = lambda : map(int, rd().strip().split())
q = int(rd())
while q:
	n = int(rd())
	a = list(rrd())
	ans = [0] * (n + 1)
	vis = [0] * (n + 1)
	for i in range(1, n + 1):
		p = []
		x = i
		while not vis[x]:
			p.append(x)
			vis[x] = 1
			x = a[x - 1]
		for j in p:
			ans[j] = len(p)
	print(' '.join(map(str, ans[1:n + 1])))
	q -= 1


for _ in range(int(input())):
	n = int(input())
	lis = list(map(int, input().split()))
	for i in range(n):
		cur = lis[i]
		ans = 1
		while cur != i + 1:
			ans += 1
			cur = lis[cur - 1]
		print(ans, end=' ')
	print()


from collections import deque
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	for i in range(n):
		arr[i] -= 1
	cycles = deque()
	for (i, num) in enumerate(arr):
		if num is not None:
			cycles.append(set())
			while num is not None:
				cycles[-1].add(num)
				tmp = i
				i = arr[tmp]
				arr[tmp] = None
				if i is not None:
					num = arr[i]
				else:
					break
	for cycle in cycles:
		for elem in cycle:
			arr[elem] = len(cycle)
	print(*arr)


q = int(input())
for i in range(q):
	a = int(input())
	cycle = [1 for i in range(a)]
	tab = list(map(int, input().split()))
	for (indice, j) in enumerate(tab):
		if cycle[indice] != 1:
			continue
		var = indice + 1
		while tab[var - 1] != indice + 1:
			var = tab[var - 1]
			cycle[indice] += 1
		var = indice + 1
		while tab[var - 1] != indice + 1:
			var = tab[var - 1]
			cycle[var - 1] = cycle[indice]
	print(*cycle)


q = int(input())
for j in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	days = []
	for i in range(n):
		f = a[a[i] - 1]
		if a[i] == f:
			days.append(1)
			continue
		if f - 1 == i:
			days.append(2)
			continue
		else:
			child = a[f - 1]
			count = 2
			for j in range(2, n):
				count += 1
				if child - 1 == i:
					days.append(count)
					break
				child = a[child - 1]
	print(' '.join((str(x) for x in days)))


from collections import Counter
from collections import defaultdict
import math
import random
import heapq as hq
from math import sqrt
import sys

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

def tinput():
	return input().split()

def rinput():
	return map(int, tinput())

def rlinput():
	return list(rinput())
mod = int(1000000000.0) + 7

def root(parent, a):
	while parent[a] != a:
		parent[a] = parent[parent[a]]
		a = parent[a]
	return a

def union(parent, size, a, b):
	(root_a, root_b) = (root(parent, a), root(parent, b))
	if root_a == root_b:
		return
	if size[root_a] >= size[root_b]:
		parent[root_b] = root_a
		size[root_a] += size[root_b]
		size[root_b] = 0
	else:
		parent[root_a] = root_b
		size[root_b] += size[root_a]
		size[root_a] = 0

def solve(a, n):
	temp = [-1] * n
	size = [0] * n
	for i in range(n):
		s = i
		while temp[s] == -1:
			temp[s] = i
			size[i] += 1
			s = a[s] - 1
	for i in range(n):
		print(size[temp[i]], end=' ')
	print()
for _ in range(iinput()):
	n = int(input())
	a = rlinput()
	solve(a, n)


q = int(input())
for sub_q in range(q):
	n = int(input())
	p = [0] + [int(i) for i in input().split()]
	ans = [0 for i in range(n)]
	for i in range(1, n + 1):
		if ans[i - 1] == 0:
			cur_list = [i]
			j = i
			if p[i] == i:
				ans[i - 1] = 1
			else:
				while p[j] != i:
					cur_list.append(p[j])
					j = p[j]
				cur_list = set(cur_list)
				for j in cur_list:
					ans[j - 1] = len(cur_list)
	print(*ans)


for q in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	(globalset, final) = (set(), [0] * n)
	for i in a:
		if len(globalset) == n:
			break
		if i in globalset:
			continue
		(kniga, localset) = (i, set())
		while kniga not in localset:
			localset.add(kniga)
			kniga = a[kniga - 1]
		globalset |= localset
		for j in localset:
			final[j - 1] = len(localset)
	print(*final)


def solve_book_passing(book_passing):
	result = []
	for child_index in range(len(book_passing)):
		pass_count = 1
		book_next_pos = book_passing[child_index] - 1
		while book_next_pos != child_index:
			pass_count += 1
			book_next_pos = book_passing[book_next_pos] - 1
		result.append(pass_count)
	return result
num_queries = int(input())
results = []
for _ in range(num_queries):
	size_arr = input()
	book_passing = [int(string) for string in input().split(' ')]
	sol = solve_book_passing(book_passing)
	results.append(' '.join([str(x) for x in sol]))
for r in results:
	print(r)


def fact(x):
	if x == 0:
		return 1
	else:
		return x * fact(x - 1)

def lower_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer

def upper_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] <= num:
			answer = middle
			start = middle + 1
		else:
			end = middle - 1
	return answer

def abs(x):
	return x if x >= 0 else -x

def binary_search(li, val, lb, ub):
	ans = 0
	while lb <= ub:
		mid = (lb + ub) // 2
		if li[mid] > val:
			ub = mid - 1
		elif val > li[mid]:
			lb = mid + 1
		else:
			ans = 1
			break
	return ans

def sieve_of_eratosthenes(n):
	ans = []
	arr = [1] * (n + 1)
	(arr[0], arr[1], i) = (0, 0, 2)
	while i * i <= n:
		if arr[i] == 1:
			j = i + i
			while j <= n:
				arr[j] = 0
				j += i
		i += 1
	for k in range(n):
		if arr[k] == 1:
			ans.append(k)
	return ans

def nc2(x):
	if x == 1:
		return 0
	else:
		return x * (x - 1) // 2

def kadane(x):
	sum_so_far = 0
	current_sum = 0
	for i in x:
		current_sum += i
		if current_sum < 0:
			current_sum = 0
		else:
			sum_so_far = max(sum_so_far, current_sum)
	return sum_so_far

def mex(li):
	check = [0] * 1001
	for i in li:
		check[i] += 1
	for i in range(len(check)):
		if check[i] == 0:
			return i

def sumdigits(n):
	ans = 0
	while n != 0:
		ans += n % 10
		n //= 10
	return ans

def product(li):
	ans = 1
	for i in li:
		ans *= i
	return ans

def maxpower(n, k):
	cnt = 0
	while n > 1:
		cnt += 1
		n //= k
	return cnt
from math import *
from collections import deque
max_steps = 100005
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [0] * n
	for i in range(n):
		if ans[i] == 0:
			li = []
			li.append(i + 1)
			k = a[i]
			steps = 1
			while k != i + 1:
				steps += 1
				li.append(k)
				k = a[k - 1]
			for j in li:
				ans[j - 1] = steps
	print(*ans)


q = int(input())
for _ in range(q):
	n = int(input())
	p = [int(i) - 1 for i in input().split()]
	d = [0] * n
	for i in range(n):
		next = p[i]
		d[i] = 1
		while True:
			if next != i:
				next = p[next]
				d[i] += 1
			else:
				break
	print(*d)


for _ in range(int(input())):
	n = int(input())
	p = [0] + list(map(int, input().split()))
	ans = ''
	for i in range(1, n + 1):
		t = i
		d = 1
		while t != p[i]:
			i = p[i]
			d += 1
		ans += str(d) + ' '
	print(ans)


R = lambda : map(int, input().split())

def f(i, j):
	j += 1
	k = a[i - 1]
	if k in s:
		s.remove(k)
		j = f(k, j)
	r[i - 1] = j
	return j
(q,) = R()
for _ in [0] * q:
	(n,) = R()
	a = (*R(),)
	s = {*a}
	r = [0] * n
	while s:
		f(s.pop(), 0)
	print(*r)


import sys
input = sys.stdin.readline
sys.setrecursionlimit(100000)

def getN():
	return int(input())

def getList():
	return list(map(int, input().split()))
import math

class UnionFind:

	def __init__(self, n):
		self.par = [i for i in range(n + 1)]
		self.rank = [0] * (n + 1)
		self.size = [1] * (n + 1)

	def find(self, x):
		if self.par[x] == x:
			return x
		else:
			self.par[x] = self.find(self.par[x])
			return self.par[x]

	def union(self, x, y):
		x = self.find(x)
		y = self.find(y)
		if self.rank[x] < self.rank[y]:
			self.par[x] = y
			self.size[y] += self.size[x]
		else:
			self.par[y] = x
			self.size[x] += self.size[y]
			if self.rank[x] == self.rank[y]:
				self.rank[x] += 1

	def same_check(self, x, y):
		return self.find(x) == self.find(y)

def solve():
	n = getN()
	nums = getList()
	uf = UnionFind(n)
	for (i, num) in enumerate(nums):
		uf.par[i + 1] = uf.find(i + 1)
		uf.par[num] = uf.find(num)
		if not uf.same_check(i + 1, num):
			uf.union(i + 1, num)
	for i in range(n + 1):
		uf.find(i)
	ans = []
	for i in range(n):
		ans.append(uf.size[uf.par[i + 1]])
	print(*ans)

def main():
	q = getN()
	for _ in range(q):
		solve()
main()


q = int(input())
for _ in range(q):
	n = int(input())
	p = list(map(int, input().split()))
	res = [0] * n
	for i in range(n):
		p[i] -= 1
	remaining = set(p)
	for i in range(n):
		if i not in remaining:
			continue
		count = 1
		path = p[i]
		inter = {path}
		remaining.discard(path)
		while path != i:
			path = p[path]
			count += 1
			inter.add(path)
			remaining.discard(path)
		for j in inter:
			res[j] = count
	print(*res)


exec('\nclass DSU:\n    def __init__(self, length):\n        self.length = length\n        self.parent = [-1] * self.length\n\n    def getParent(self, node, start):\n        if node >= self.length:\n            return False\n        if self.parent[node] < 0:\n            if start != node:\n                self.parent[start] = node\n            return node\n        return self.getParent(self.parent[node], start)\n\n    def union(self, node1, node2):\n        parent1 = self.getParent(node1, node1)\n        parent2 = self.getParent(node2, node2)\n\n        if parent1 == parent2:\n            return False\n        elif self.parent[parent1] <= self.parent[parent2]:\n            self.parent[parent1] += self.parent[parent2]\n            self.parent[parent2] = parent1\n        else:\n            self.parent[parent2] += self.parent[parent1]\n            self.parent[parent1] = parent2\n        return True\n\n    def getCount(self, node):  \n        return -self.parent[self.getParent(node, node)]\n')

def solve(n, lst):
	dsu = DSU(n)
	for i in range(n):
		dsu.union(i, lst[i] - 1)
	for i in lst:
		print(dsu.getCount(i - 1), end=' ')
for _ in range(int(input())):
	n = int(input())
	lst = list(map(int, input().split()))
	solve(n, lst)
	print()


for _ in range(int(input())):
	n = int(input())
	l = [int(i) - 1 for i in input().split()]
	res = []
	v = [0] * n
	for i in range(n):
		if v[i] == 0:
			temp = i
			v[temp] = 1
			res.append({temp})
			while l[temp] not in res[-1]:
				res[-1].add(l[temp])
				temp = l[temp]
				v[temp] = 1
	for i in res:
		for j in i:
			v[j] = len(i)
	print(*v)


def dfs(graph, node, visited, final):
	if visited[node]:
		return final
	visited[node] = True
	if not visited[graph[node - 1]]:
		i = graph[node - 1]
		dfs(graph, i, visited, final)
		final.append(i)
t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(p) for p in input().split()]
	visited = [False] * (n + 1)
	days = [1] * (n + 1)
	for i in range(len(arr)):
		if not visited[arr[i]]:
			final = [arr[i]]
			dfs(arr, arr[i], visited, final)
			for j in range(len(final)):
				days[final[j]] = len(final)
	days.pop(0)
	print(*days)


queries = []
querlen = []
q = int(input())
for i in range(q):
	n = int(input())
	querlen.append(n)
	a = input().split()
	query = [int(b) for b in a]
	queries.append(query)
for (countq, q) in enumerate(queries):
	out = [0] * querlen[countq]
	for num in q:
		if out[num - 1] == 0:
			count = 0
			p = num
			cycles = set()
			while p not in cycles:
				count += 1
				cycles.add(p)
				p = q[p - 1]
			else:
				for kid in cycles:
					out[kid - 1] = count
		else:
			continue
	newres = list(map(str, out))
	result = ' '.join(newres)
	print(result)


from sys import stdout, stdin
for i in stdin:
	q = int(i)
	break
for i in range(q):
	for j in stdin:
		n = int(j)
		break
	l = []
	for j in stdin:
		l = list(map(int, j.strip().split()))
		break
	a = [0 for i in range(n)]
	for j in l:
		if a[j - 1] == 0:
			t = [j]
			k = 1
			current = l[j - 1]
			while current != j:
				t.append(current)
				current = l[current - 1]
				k += 1
			for m in t:
				a[m - 1] = k
	a = list(map(str, a))
	stdout.write(' '.join(a) + '\n')


alph = 'abcdefghijklmnopqrstuvwxyz'
q = int(input())
for i in range(q):
	n = int(input())
	arr = [-1] * n
	p = list(map(int, input().split()))
	for j in range(n):
		d = [j + 1]
		k = p[j] - 1
		if p[j] == j + 1:
			print(1, end=' ')
		elif arr[j] == -1:
			for t in range(n):
				if p[k] != j + 1:
					d.append(p[k])
					k = p[k] - 1
				else:
					break
			for t in range(len(d)):
				arr[d[t] - 1] = len(d) + 1
			print(len(d) + 1, end=' ')
		else:
			print(arr[j], end=' ')
	print('')


import sys
import time
prev_time = time.time()
read = sys.stdin.readline

def solution():
	global n
	res = [0 for _ in range(n)]
	for i in range(1, n + 1):
		if res[i - 1] != 0:
			continue
		cnt = 1
		num = p_list[i - 1]
		num_list = []
		num_list.append(num)
		for _ in range(n):
			if i == num:
				break
			num = p_list[num - 1]
			num_list.append(num)
			cnt += 1
		for nl in num_list:
			res[nl - 1] = cnt
	return res
q = int(read().strip())
for i in range(q):
	n = int(read().strip())
	p_list = list(map(int, read().strip().split()))
	for j in solution():
		print(j, end=' ')
	print()


def main_function(p):
	l = len(p)
	result = [0] * l
	while p != [0] * l:
		i = 0
		while p[i] == 0:
			i += 1
		temp_cycle_list = []
		initial_no = p[i]
		temp_no = p[initial_no - 1]
		while temp_no != initial_no:
			temp_cycle_list.append(temp_no)
			temp_no = p[temp_no - 1]
		temp_cycle_list.append(temp_no)
		length_of_cycle = len(temp_cycle_list)
		for j in temp_cycle_list:
			result[j - 1] = length_of_cycle
			p[j - 1] = 0
	return result
for _ in range(int(input())):
	n = int(input())
	p = list(str(input()).split(' '))
	p = [int(x) for x in p]
	if p.sort == p:
		result = [1] * len(p)
	else:
		result = main_function(p)
	for i in result:
		print(i, end=' ')
	print()


q = int(input())
for i in range(0, q):
	n = int(input())
	p = input().split(' ')
	p = [int(p[i]) - 1 for i in range(0, n)]
	viz = [0] * n
	ans = [0] * n
	for i in range(0, n):
		if viz[i] == 0:
			cycle = list()
			pos = i
			sol = 0
			while viz[pos] == 0:
				viz[pos] = 1
				cycle.append(pos)
				pos = p[pos]
				sol += 1
			for j in cycle:
				ans[j] = sol
	for i in ans:
		print(i, end=' ')
	print()


q = int(input())

def solve():
	n = int(input())
	p = [int(x) for x in input().split()]
	days = [0] * n
	d = 0
	for i in range(n):
		if days[i] != 0:
			continue
		d = 0
		j = p[i] - 1
		d += 1
		s = [i]
		while j != i:
			s.append(j)
			d += 1
			j = p[j] - 1
		for k in s:
			days[k] = str(d)
	print(' '.join(days))
for _ in range(q):
	solve()


q = int(input())
for _ in range(q):
	n = int(input())
	p = list(map(int, input().split()))
	res = []
	for i in range(n):
		j = p[i] - 1
		c = 1
		while j != i:
			c += 1
			j = p[j] - 1
		res.append(c)
	print(*res)


import math
from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	ans = [0] * n
	for i in range(n):
		count = 1
		x = p[i] - 1
		arr = [x]
		if not ans[i]:
			while p[i] != p[x]:
				x = p[x] - 1
				count += 1
				arr.append(x)
			for i in arr:
				ans[i] = count
			ans[i] = count
	print(*ans)


q = int(input())
while q:
	n = int(input())
	arr = [int(i) for i in input().split()]
	(next_var, answer) = (0, 0)
	for i in range(n):
		answer = arr[i]
		cnt = 1
		while i + 1 != answer:
			next_var = answer
			answer = arr[next_var - 1]
			cnt += 1
		print(cnt, end=' ')
	print()
	q -= 1


def dfs(u, isv, e, rev):
	rev.append(u)
	isv[u] = True
	for v in e[u]:
		if not isv[v]:
			dfs(v, isv, e, rev)
q = int(input())
for _ in range(q):
	n = int(input())
	e = []
	isv = []
	rev = []
	ans = []
	for i in range(n + 1):
		e.append([])
		isv.append(False)
		ans.append(0)
	p = [int(x) for x in input().split()]
	for i in range(len(p)):
		e[i + 1].append(p[i])
	for i in range(1, n + 1):
		if not isv[i]:
			dfs(i, isv, e, rev)
			for v in rev:
				ans[v] = len(rev)
			rev.clear()
	for i in range(1, n + 1):
		print(ans[i], end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	for t in a:
		q = t
		p = 1
		while 1:
			if a[t - 1] == q:
				print(str(p) + ' ', end='')
				break
			else:
				t = a[t - 1]
				p += 1
	print('\n')


q = int(input())
out = []
for _ in range(q):
	input()
	p = list(map(lambda x: int(x) - 1, input().split()))
	o = [0 for _ in range(len(p))]
	u = set(range(len(p)))
	while u:
		n = next(iter(u))
		v = {n}
		d = 0
		while True:
			d += 1
			n = p[n]
			if n in v:
				break
			v.add(n)
		u.difference_update(v)
		for n in v:
			o[n] = d
	out.append(' '.join(map(str, o)))
print('\n'.join(out))


import sys

def main():
	for tc in range(int(input())):
		n = int(input())
		arr = get_array()
		ans = [1] * n
		for i in range(n):
			j = arr[i] - 1
			while j != i:
				ans[i] += 1
				j = arr[j] - 1
		print(*ans)
get_array = lambda : list(map(int, sys.stdin.readline().split()))
get_ints = lambda : map(int, sys.stdin.readline().split())
input = lambda : sys.stdin.readline().strip()
main()


q = int(input())
for i in range(q):
	n = int(input())
	p = list(map(int, input().strip().split()))
	output = []
	for k in range(n):
		tmp_days = 1
		tmp_index = p[k] - 1
		while tmp_index != k:
			tmp_index = p[tmp_index] - 1
			tmp_days += 1
		output.append(tmp_days)
	print(*output)


q = int(input())
for i in range(q):
	n = int(input())
	d = list(map(int, input().split()))
	for j in range(n):
		count = 1
		x = d[j]
		while d[x - 1] != j + 1:
			x = d[x - 1]
			count += 1
		if d[j] == j + 1:
			print(count, end=' ')
		else:
			print(count + 1, end=' ')
	print()


q = int(input())

def check(n, p):
	ans = [0] * n
	for i in range(n):
		group = []
		k = 1
		if p[i] != 0:
			j = p[i]
			group.append(i + 1)
			while j != i + 1:
				k += 1
				group.append(j)
				j = p[j - 1]
			for a in group:
				ans[a - 1] = k
				p[a - 1] = 0
	return ans
for _ in range(q):
	n = int(input())
	p = list(map(int, input().split()))
	m = check(n, p)
	print(*m)


import math
from sys import stdin, stdout
from collections import defaultdict

def pnt(x):
	stdout.write(str(x) + '\n')

def pnt(x, end=' '):
	stdout.write(str(x) + end)
inp = lambda : int(stdin.readline())
sip = lambda : input()
mulip = lambda : map(int, input().split())
lst = lambda : list(map(int, stdin.readline().split()))
sarr = lambda : list(map(str, stdin.readline().split()))
slst = lambda : list(sip())
arr2d = lambda N: [[int(x) for x in input().split()] for i in range(N)]
for _ in range(inp()):
	n = inp()
	A = [0]
	_ = [A.append(int(x)) for x in input().split()]
	res = [0] * (n + 1)
	d = defaultdict(list)
	used = [True] * (n + 1)
	for i in range(1, n + 1):
		j = A[i]
		if used[i]:
			d[i].append(i)
		cnt = 1
		while j != i and used[i]:
			d[i].append(j)
			used[j] = False
			j = A[j]
	for i in d:
		for j in d[i]:
			res[j] = len(d[i])
	for i in range(1, n + 1):
		print(res[i], end=' ')
	print()


q = int(input())
l = []
for i in range(q):
	n = int(input())
	w = list(map(int, input().split()))
	for j in range(n):
		pos = w[j] - 1
		ans = 1
		while pos != j:
			ans += 1
			pos = w[pos] - 1
		l.append(ans)
	print(*l)
	l.clear()


t = int(input())
for i in range(t):
	y = int(input())
	l = [i for i in range(1, y + 1)]
	r = list(l)
	u = list(map(int, input().split()))
	for i in range(1, y + 1):
		yu = u[i - 1]
		count = 1
		while yu != i:
			yu = u[yu - 1]
			count += 1
		print(count, end=' ')
	print()


import sys
try:
	(sys.stdin, sys.stdout) = (open('in.txt', 'r'), open('out.txt', 'w'))
except:
	pass
ii1 = lambda : int(sys.stdin.readline().strip())
is1 = lambda : sys.stdin.readline().strip()
iia = lambda : list(map(int, sys.stdin.readline().strip().split()))
isa = lambda : sys.stdin.readline().strip().split()
mod = int(1000000000.0 + 7)
from collections import *
from math import *
for _ in range(ii1()):
	n = ii1()
	arr = iia()
	for i in range(n):
		arr[i] -= 1
	res = []
	for i in range(n):
		itself = arr[i]
		ans = 0
		ii = i
		while ii != itself:
			ans += 1
			itself = arr[itself]
		res.append(ans + 1)
	print(*res)


for _ in range(int(input())):
	kids = int(input())
	order = list(map(int, input().split()))
	used = set()
	re = [None] * kids
	for j in range(1, kids + 1):
		if re[j - 1]:
			continue
		else:
			idx = order[j - 1]
			days = 1
			group = set()
			group.add(idx)
			while j != idx:
				temp = order[idx - 1]
				idx = temp
				group.add(idx)
				days += 1
			for i in group:
				re[i - 1] = days
	print(*re)


def ft(L, x):
	nb = 0
	i = x
	Tab = []
	while True:
		i = L[i - 1]
		nb += 1
		Tab.append(i)
		if i == x:
			return (Tab, nb)

def remplir(T, L, x):
	couple = ft(L, x)
	n = couple[1]
	tab = couple[0]
	for i in range(n):
		T[tab[i] - 1] = n
	return T

def affichage(L):
	for i in range(len(L)):
		L[i] = str(L[i])
	return ' '.join(L)
m = int(input())
for i in range(m):
	n = int(input())
	ch = input()
	L = [int(i) for i in ch.split(' ')]
	T = len(L) * [0]
	for j in range(len(L)):
		if T[j] == 0:
			T = remplir(T, L, j + 1)
	print(affichage(T))


def switch_books(kids):
	res = [1] * len(kids)
	for i in range(len(kids)):
		if kids[i] == i + 1:
			continue
		elif res[i] == 1:
			node = []
			cur = kids[i]
			while kids[cur - 1] != cur and cur not in node:
				node.append(cur)
				cur = kids[cur - 1]
			for n in node:
				res[n - 1] += len(node) - 1
	return res
q = int(input())
for i in range(q):
	n = input()
	kids = list(map(int, input().split()))
	print(' '.join(map(str, switch_books(kids))))


tests = int(input())
for _ in range(tests):
	n = int(input())
	arr = list(map(int, input().split()))
	pres = [0 for i in range(n)]
	for i in range(n):
		if not pres[i]:
			moove = 1
			currInd = arr[i]
			aa = [i + 1, arr[i]]
			while currInd != i + 1:
				moove += 1
				aa.append(arr[currInd - 1])
				currInd = arr[currInd - 1]
			for el in aa:
				pres[el - 1] = moove
		else:
			continue
	print(' '.join(map(str, pres)))


for _ in range(int(input())):
	n = int(input())
	p = [int(x) for x in input().split()]
	t = [0] * n
	for i in range(n):
		if not t[i]:
			x = p[i] - 1
			c = {i, x}
			while x != i:
				x = p[x] - 1
				c.add(x)
			for j in c:
				t[j] = len(c)
	print(*t)


R = lambda : map(int, input().split())
(q,) = R()
for _ in [0] * q:
	(n,) = R()
	a = (*R(),)
	s = {*a}
	r = [0] * n
	while s:
		x = s.pop()
		t = [x]
		while a[x - 1] in s:
			x = a[x - 1]
			s -= {x}
			t += (x,)
		for x in t:
			r[x - 1] = len(t)
	print(*r)


import sys
from collections import deque
input = sys.stdin.readline

def bfs(root):
	q = [root]
	q = deque(q)
	count = 1
	while len(q) != 0:
		e = q.popleft()
		done[e] = 1
		for i in graph[e]:
			if done[i] == 0:
				q.append(i)
				parent[i] = e
				count += 1
			else:
				s = e
				ans[s] = count
				while parent[s] != -1:
					s = parent[s]
					ans[s] = count
for nt in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	graph = [[] for i in range(n)]
	for i in range(n):
		graph[i].append(a[i] - 1)
	done = [0] * n
	parent = [-1] * n
	ans = [0] * n
	for i in range(n):
		if done[i] == 0:
			bfs(i)
			done[i] = 1
	print(*ans)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for j in range(int(input())):
	n = int(input())
	vals = list(map(int, input().split()))
	visited = set([])
	ans = [0 for s in range(n)]
	for s in range(n):
		v0 = vals[s] - 1
		if not v0 in visited:
			temp = v0
			vis = set([v0])
			visited.add(v0)
			while vals[temp] - 1 != v0:
				v1 = vals[temp] - 1
				temp = v1
				vis.add(v1)
				visited.add(v1)
			for b in vis:
				ans[b] = len(vis)
	print(*ans)


num_queries = int(input())
for _ in range(num_queries):
	num_kids = int(input())
	p = list(map(int, input().split(' ')))
	days = [0] * num_kids
	for i in range(num_kids):
		if days[i] == 0:
			count = 1
			current = p[i]
			kids = {current}
			while current != i + 1:
				current = p[current - 1]
				kids.add(current)
				count += 1
			for kid in kids:
				days[kid - 1] = count
	print(' '.join(map(str, days)))


t = int(input())

def solve():
	n = int(input())
	g = [[] for i in range(n)]
	p = list(map(lambda x: int(x) - 1, input().split()))
	for i in range(n):
		g[i].append(p[i])
	ans = [0 for i in range(n)]
	visited = [False for i in range(n)]
	for i in range(n):
		if not visited[i]:
			l = []
			while not visited[i]:
				l.append(i)
				visited[i] = True
				i = p[i]
			for i in l:
				ans[i] = len(l)
	for i in ans:
		print(i, end=' ')
	print()
for _ in range(t):
	solve()


for _ in range(int(input())):
	x = int(input())
	a = list(map(int, input().split()))
	l = list(a)
	l.sort()
	e = []
	s = 0
	for i in range(x):
		c = 1
		s = a[i]
		while s != i + 1:
			c += 1
			t = a[s - 1]
			s = t
		e.append(c)
	print(*e)


for _ in range(int(input())):
	n = int(input())
	a = [*map(int, input().split())]
	ans = [-1] * n
	for i in range(n):
		if ans[i] != -1:
			continue
		c = a[i] - 1
		t = [i]
		res = 1
		while a[c] != a[i]:
			t.append(c)
			c = a[c] - 1
			res += 1
		for j in t:
			ans[j] = res
	print(*ans)


import sys

def I():
	return sys.stdin.readline().rstrip()
q = int(I())
for _ in range(q):
	n = int(I())
	c = [-1] * n

	def getp(i):
		s = []
		while c[i] >= 0:
			s.append(i)
			i = c[i]
		for j in s:
			c[j] = i
		return i
	p = list(map(int, I().split()))
	p = [i - 1 for i in p]
	for (i, q) in enumerate(p):
		(a, b) = (getp(i), getp(q))
		if a != b:
			c[a] += c[b]
			c[b] = a
	for i in p:
		print(-c[getp(i)], end=' ')
	print()


import sys
input = sys.stdin.readline

def main():
	q = int(input())
	for _ in range(q):
		N = int(input())
		P = [int(x) for x in input().split()]
		dp = [[0 for i in range(N + 1)] for j in range(N + 1)]
		ans = [0] * N
		for i in range(N):
			count = 0
			prev = i
			next = P[i] - 1
			while True:
				if dp[prev][next] != 0:
					count += dp[prev][next]
				else:
					count += 1
				dp[i][next] = count
				dp[prev][next] = 1
				if i == next:
					break
				prev = next
				next = P[next] - 1
			ans[i] = count
		print(*ans)
main()


def solve(arr, n):
	ans = [1] * n
	for i in range(n):
		count = 0
		c = i
		while i != arr[c]:
			ind = arr[c]
			c = ind
			count += 1
		ans[i] += count
	for val in ans:
		print(val, end=' ')
	print('\n', end='')
t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(x) - 1 for x in input().split()]
	solve(arr, n)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l1 = []
	for i in range(n):
		c = 1
		p = i
		while i + 1 != l[p]:
			p = l[p] - 1
			c += 1
		l1.append(c)
	for i in l1:
		print(i, end=' ')
	print()


def lol(x, l):
	cnt = 1
	i = l[x]
	while not x == i:
		i = l[i]
		cnt += 1
	return cnt
for _ in range(int(input())):
	n = input()
	l = [int(i) - 1 for i in input().split()]
	x = []
	for i in range(len(l)):
		x.append(lol(i, l))
	print(*x)


def solve():
	input()
	arr = [int(x) for x in input().split()]
	result = []
	for i in range(len(arr)):
		hops = 1
		index = arr[i] - 1
		target = i
		while index != target:
			hops += 1
			index = arr[index] - 1
		result.append(hops)
	res = ''
	for i in result:
		res += str(i) + ' '
	print(res)

def main():
	t = int(input())
	while t > 0:
		solve()
		t -= 1
main()


def solve(n, p_s):
	sets = []
	visited = set([])
	for (i, p) in enumerate(p_s):
		if i in visited:
			continue
		new_indices = set([])
		cur = i
		while True:
			if cur in new_indices:
				break
			new_indices.add(cur)
			visited.add(cur)
			cur = p_s[cur] - 1
		sets.append(new_indices)
	ans = [0 for _ in range(n)]
	for indices in sets:
		for index in indices:
			ans[index] = str(len(indices))
	return ' '.join(ans)
t = int(input())
for _ in range(t):
	n = int(input())
	p_s = [int(r) for r in input().split(' ')]
	print(solve(n, p_s))


q = int(input())
total = []
for qi in range(q):
	n = int(input())
	kids = list(map(int, input().split()))
	current = [0] * n
	for i in range(n):
		current[kids[i] - 1] = kids[i]
	answers = [0] * n
	found = 0
	for i in range(n):
		if current[i] == kids[i]:
			answers[i] = 1
			found += 1
	days = 1
	while found < n:
		tmp = [0] * n
		for i in range(n):
			tmp[kids[i] - 1] = current[i]
		for i in range(n):
			if current[i] == kids[i] and answers[i] == 0:
				answers[i] = days
				found += 1
		days += 1
		current = tmp
	total.append(answers)
for t in total:
	print(' '.join([str(i) for i in t]))


def Solve(data):
	res = [-1] * len(data)
	for x in range(len(res)):
		if res[x] == -1:
			CorpMatch(data, x, res)
	for x in range(len(res)):
		if x != len(res) - 1:
			print(res[x], end=' ')
		else:
			print(res[x])

def CorpMatch(data, x, res):
	j = data[x]
	K = []
	num = 1
	while j != x:
		num += 1
		K.append(j)
		j = data[j]
	for m in range(len(K)):
		res[K[m]] = num
	res[x] = num
t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	data = [int(x) - 1 for x in input().split()]
	Solve(data)


for rpt in range(int(input())):
	kcount = int(input())
	kids = [int(x) - 1 for x in input().split(' ')]
	reskids = [0 for x in range(kcount)]
	for i in range(kcount):
		if reskids[i] == 0:
			if kids[i] == i:
				reskids[i] = 1
			else:
				fn = kids[i]
				cycle = [fn]
				current = kids[fn]
				while not current == fn:
					cycle.append(current)
					current = kids[current]
				fnres = len(cycle)
				if fnres == kcount:
					reskids = [fnres for x in range(kcount)]
					break
				else:
					for i in cycle:
						reskids[i] = fnres
	res = ''
	for i in reskids:
		res += str(i) + ' '
	print(res)


q = int(input())
for qq in range(q):
	n = int(input())
	P = list(map(int, input().split()))
	P.insert(0, 0)
	root = list(range(n + 1))
	cnt = list(range(n + 1))
	for i in range(0, n + 1):
		cnt[i] = 1

	def getroot(u):
		if root[u] == u:
			return u
		else:
			root[u] = getroot(root[u])
			return root[u]
	for i in range(1, n + 1):
		cnt[getroot(i)] = cnt[getroot(i)] + cnt[getroot(P[i])]
		root[getroot(P[i])] = getroot(i)
	for i in range(1, n + 1):
		print(cnt[getroot(i)] // 2, end=' ')
	print()


tests = int(input())
for te in range(tests):
	n = int(input())
	arr = list(map(int, input().split()))
	for i in range(n):
		arr[i] -= 1
	ans = [0 for i in range(n)]
	for i in range(n):
		cur = i
		count = 0
		for j in range(n):
			index = arr[cur]
			count += 1
			if i == index:
				ans[i] = count
				break
			cur = index
	print(*ans)


import sys
sys.setrecursionlimit(10 ** 6)

def dfs(a, par=-1):
	global xx
	cpar = par
	if par == -1:
		cpar = a
	i = adj[a]
	if i in xx:
		return
	if i == cpar:
		return
	xx.add(i)
	dfs(i, cpar)
q = int(input())
for _ in range(q):
	n = int(input())
	it = list(map(int, input().split()))
	ans = [-1 for i in range(n)]
	ind = 0
	while ind < n:
		while ind < n:
			if ans[ind] == -1:
				break
			ind += 1
		if ind == n:
			continue
		arr = [ind]
		if it[0] - 1 == ind:
			ans[ind] = 1
		else:
			arr.append(it[ind] - 1)
			while arr[0] != arr[-1] and len(arr) < 2 * n:
				arr.append(it[arr[-1]] - 1)
			for i in arr:
				ans[i] = len(arr) - 1
	print(*ans)


import sys
sys.setrecursionlimit(1000000)
from collections import deque

def rec(ii, start, cnt):
	if cnt > n:
		return n
	if ans[ii] != -1:
		return cnt
	if ii == start:
		ans[ii] = cnt
		return cnt
	ansi = rec(arr[ii], start, cnt + 1)
	ans[ii] = ansi
	return ansi
for t in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr = [x - 1 for x in arr]
	ans = [-1 for _ in range(n)]
	vis = set()
	for (i, x) in enumerate(arr):
		if i not in vis:
			cycle = [i]
			vis.add(i)
			j = arr[i]
			while j != i:
				vis.add(j)
				cycle.append(j)
				j = arr[j]
			for j in cycle:
				ans[j] = len(cycle)
	try:
		print(*ans)
	except Exception as e:
		print('wrong answer')


def main():
	Q = int(input())
	for query in range(Q):
		N = int(input())
		P = [int(i) - 1 for i in input().split()]
		par = [i for i in range(N)]
		rank = [1 for i in range(N)]

		def find_root(x):
			if par[x] == x:
				return x
			else:
				par[x] = find_root(par[x])
				return par[x]

		def is_same_group(x, y):
			return find_root(x) == find_root(y)

		def unite(x, y):
			x = find_root(x)
			y = find_root(y)
			if x == y:
				return
			if rank[x] < rank[y]:
				(x, y) = (y, x)
			rank[x] += rank[y]
			par[y] = x

		def size(x):
			return rank[find_root(x)]
		for (i, p) in enumerate(P):
			unite(i, p)
		ans = []
		for i in range(N):
			ans.append(size(i))
		print(*ans)
main()


q = int(input())
for i in range(q):
	n = int(input())
	a = [int(i) for i in input().split()]
	b = [0] * n
	d = {}
	for i in range(len(a)):
		d[i + 1] = a[i]
	for i in range(1, n + 1):
		if b[i - 1] == 0:
			j = i
			k = 1
			while d[j] != i:
				j = d[j]
				k += 1
			b[i - 1] = k
			j = i
			while d[j] != i:
				j = d[j]
				b[j - 1] = k
	for i in b:
		print(i, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	p = [int(x) - 1 for x in input().split()]
	used = [False] * n
	r = [0] * n
	for i in range(n):
		if not used[i]:
			j = i
			cycle = []
			while not used[j]:
				cycle.append(p[j])
				used[j] = True
				j = p[j]
			for c in cycle:
				r[c] = len(cycle)
	print(*r)


import sys
input = lambda : sys.stdin.readline()
MOD = 1000000007
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : list(map(int, input().split()))
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())
for _ in range(ii()):
	n = ii()
	l = il()
	d = dict()
	for i in range(1, n + 1):
		d[i] = l[i - 1]
	for i in range(1, n + 1):
		c = 1
		x = d[i]
		while i != x:
			x = d[x]
			c += 1
		print(c, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	ans = []
	for i in range(n):
		count = 1
		temp = p[i] - 1
		while p[i] != p[temp]:
			temp = p[temp] - 1
			count += 1
		ans.append(count)
	print(*ans)


q = int(input())
for i in range(0, q):
	n = int(input())
	l = list(map(int, input().split()))
	done = {}
	count = 0
	d = {}
	for j in range(1, n + 1):
		d[j] = j
	step = 0
	while count != n:
		step += 1
		for i in range(1, n + 1):
			d[i] = l[d[i] - 1]
			if d[i] == i and i not in done:
				count += 1
				done[i] = step
	for j in range(1, n + 1):
		print(done[j], end=' ')
	print()


for i in range(int(input())):
	n = int(input())
	bookList = (*map(int, input().split()),)
	for i in range(n):
		(x, counter) = (bookList[i] - 1, 1)
		while x != i:
			x = bookList[x] - 1
			counter += 1
		print(counter)


q = int(input())
while q:
	n = int(input())
	arr = list(map(int, input().split()))
	result = [-1 for _ in range(n)]
	for i in range(n):
		if result[i] == -1:
			cycle = []
			j = i
			nextone = arr[j] - 1
			cycle.append(i)
			res = 1
			while nextone != i:
				cycle.append(nextone)
				j = nextone
				nextone = arr[j] - 1
				res += 1
			for x in cycle:
				result[x] = res
	print(*result)
	q -= 1


from sys import stdin, stdout
import math
from itertools import permutations, combinations
from collections import defaultdict
from bisect import bisect_left
mod = 1000000007

def L():
	return list(map(int, stdin.readline().split()))

def In():
	return map(int, stdin.readline().split())

def I():
	return int(stdin.readline())

def printIn(ob):
	return stdout.write(str(ob) + '\n')

def powerLL(n, p):
	result = 1
	while p:
		if p & 1:
			result = result * n % mod
		p = int(p / 2)
		n = n * n % mod
	return result
import sys

def myCode():
	n = I()
	A = L()
	d = {}
	for i in A:
		d[i] = 0
	for i in range(1, n + 1):
		if d[i] == 0:
			cnt = 0
			tmp = A[i - 1]
			lst1 = [tmp]
			while i != tmp:
				cnt += 1
				tmp = A[tmp - 1]
				lst1.append(tmp)
			for i in lst1:
				d[i] = cnt + 1
	print(' '.join((str(d[i + 1]) + ' ' for i in range(n))))

def main():
	for t in range(I()):
		myCode()
main()


q = int(input())
while q:
	q -= 1
	n = int(input())
	l = list(map(int, input().split()))
	vis = [0] * (n + 1)
	ans = []
	for i in range(1, n + 1):
		temp = []
		t = i
		if vis[i] == 0:
			while 1:
				temp.append(t)
				vis[t] = 1
				if l[i - 1] == i:
					break
				t = l[t - 1]
				if l[t - 1] == i:
					vis[t] = 1
					temp.append(t)
					break
		ans.append(temp)
	fin = [0] * (n + 1)
	for i in ans:
		for j in i:
			fin[j] = len(i)
	print(*fin[1:])


from sys import stdin
input = stdin.buffer.readline
import math
q = int(input())

def pre(n):
	return int(n) - 1

def solve(p, n):

	def find(i, parent):
		if i != parent:
			dp[parent] += 1
			p[i] = find(p[i], parent)
			dp[i] = dp[parent]
		return parent
	dp = [0] * n
	for i in range(n):
		if dp[i] == 0:
			find(p[i], i)
	for i in range(n):
		print(dp[i] + 1, end=' ')
	print()
for _ in range(q):
	n = int(input())
	p = list(map(pre, input().split()))
	solve(p, n)


def back(var, p):
	now = p[var]
	day = 1
	while now != var:
		now = p[now]
		day += 1
	return day
for _ in range(int(input())):
	n = int(input())
	P = list(map(int, input().split(' ')))
	p = dict()
	for i in range(n):
		p[i + 1] = P[i]
	ans = []
	for var in range(1, n + 1):
		ans.append(back(var, p))
	print(*ans)


for i in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	a = [1] * n
	for i in range(n):
		j = i
		while i + 1 != l[j]:
			j = l[j] - 1
			a[i] += 1
	print(*a)


def p(i, l):
	count = 1
	k = l[i]
	while i != k:
		k = l[k]
		count += 1
	return count
for _ in ' ' * int(input()):
	n = int(input())
	l = [int(i) - 1 for i in input().split()]
	l1 = []
	for i in range(n):
		l1 += [p(i, l)]
	print(*l1)


from collections import defaultdict

class graph:

	def __init__(self, v):
		self.v = v
		self.graph = defaultdict(list)

	def add_edge(self, a, b):
		self.graph[a].append(b)

	def connected_components(self):
		visit = [0] * self.v
		c = []
		for i in range(self.v):
			if visit[i] == 0:
				s = [i]
				t = []
				while s:
					u = s.pop()
					if visit[u] == 0:
						t.append(u)
						visit[u] = 1
					for x in self.graph[u]:
						if visit[x] == 0:
							s.append(x)
				c.append(t)
		return c

	def solve(self):
		l = self.connected_components()
		ans = [0] * self.v
		for i in l:
			x = len(i)
			for j in i:
				ans[j] = x
		return ans
t = int(input())
for q in range(t):
	n = int(input())
	g = graph(n)
	a = list(map(int, input().split()))
	for i in range(n):
		g.add_edge(i, a[i] - 1)
	print(*g.solve())


q = int(input())

def func(sp):
	res = [0 for i in range(len(sp))]
	for i in range(len(sp)):
		if res[i] == 0:
			k = sp[i]
			loc = 1
			kek = [i]
			while k - 1 != i:
				kek.append(k - 1)
				loc += 1
				k = sp[k - 1]
			for d in kek:
				res[d] = loc
	return res
for i in range(q):
	n = int(input())
	sp = input().split()
	sp = [int(sp[i]) for i in range(n)]
	res = func(sp)
	for i in res:
		print(i, end=' ')
	print()


from collections import defaultdict

def dfs(stack, visited, g):
	cc = 0
	while stack:
		p = stack.pop()
		if visited[p] != 2:
			visited[p] += 1
			cc += 1
			if visited[p] == 2:
				return cc - 1
		for i in g[p]:
			if visited[i] != 2:
				stack.append(i)

def parent(par, a):
	if par[a] == a:
		return a
	else:
		return parent(par, par[a])

def union(par, a, b):
	(c, d) = (parent(par, a), parent(par, b))
	if c == d:
		return
	else:
		par[d] = c
t1 = int(input())
for yu in range(t1):
	t = int(input())
	g = dict()
	l = list(map(int, input().split()))
	for i in range(t):
		l[i] -= 1
	par = [i for i in range(t)]
	for i in range(t):
		union(par, i, l[i])
	dicparent = dict()
	pset = set()
	rparent = dict()
	for i in range(t):
		f = parent(par, i)
		dicparent[i] = f
		pset.add(f)
	g = defaultdict(list)
	for i in range(t):
		(a, b) = (i + 1, l[i])
		a = a - 1
		b = b
		g[a].append(b)
	for i in pset:
		visited = [0] * t
		stack = [i]
		rparent[i] = dfs(stack, visited, g)
	for i in range(t):
		print(rparent[dicparent[i]], end=' ')
	print()


ll = []
n = int(input())
for x in range(n):
	k = int(input())
	l11 = list(map(int, input().split()))
	l = []
	for y in range(k):
		l.append(l11[y] - 1)
	ll.append(l)
for x in ll:
	l = len(x)
	rr = ''
	for i in range(l):
		r = 1
		j = x[i]
		if i == x[i]:
			rr += '1' + ' '
			continue
		while True:
			if i == x[j]:
				break
			j = x[j]
			r += 1
		r += 1
		rr += str(r) + ' '
	print(rr)


q = int(input())

def find(x, root):
	if root[x] == -1:
		root[x] = x
		return x
	trace = []
	while root[x] != x:
		trace.append(x)
		x = root[x]
	for n in trace:
		root[n] = x
	return x

def union(x, y, root):
	px = find(x, root)
	py = find(y, root)
	if px != py:
		root[px] = py
for _ in range(q):
	n = int(input())
	nums = [int(x) - 1 for x in input().split()]
	root = [-1] * len(nums)
	for (i, x) in enumerate(nums):
		union(i, x, root)
	size = {}
	for i in range(len(nums)):
		root[i] = find(i, root)
	for x in root:
		if x in size:
			size[x] += 1
		else:
			size[x] = 1
	result = []
	for i in range(len(nums)):
		result.append(str(size[root[i]]))
	print(' '.join(result))


for i in range(int(input())):
	fuck = input()
	work = input().split()
	for elem in work:
		now = 0
		count = 0
		while elem != now:
			if count == 0:
				now = work[int(elem) - 1]
			else:
				now = work[int(now) - 1]
			count += 1
		print(count, end=' ')
	print()


def solution(n, permutation):
	ret = [0] * n
	for i in range(n):
		if ret[i] == 0:
			buf = [i]
			length = 1
			j = permutation[i]
			while j != i:
				buf.append(j)
				length += 1
				j = permutation[j]
			for k in buf:
				ret[k] = length
	return ret
q = int(input())
for i in range(q):
	n = int(input())
	permutation = input().split()
	permutation = [int(x) - 1 for x in permutation]
	print(' '.join(map(str, solution(n, permutation))))


q = int(input())
for _ in range(q):
	n = int(input())
	new = list(map(int, input().split()))
	ans = [0] * (n + 1)
	arr = [0]
	arr.extend(new)
	for i in range(1, len(arr)):
		day = 1
		now = arr[i]
		while now != i:
			now = arr[now]
			day += 1
		ans[i] = day
	ans = list(map(str, ans))
	print(' '.join(ans[1:]))


t = int(input())

def solve():
	n = int(input())
	p = list(map(int, input().split()))
	ret = [0 for i in range(n)]
	for i in range(n):
		ans = 1
		a = p[i]
		while a != i + 1:
			ans += 1
			a = p[a - 1]
		ret[i] = ans
	for i in ret:
		print(i, end=' ')
	print()
for _ in range(t):
	solve()


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().strip().split()))
	for i in range(n):
		k = l[i]
		c = 1
		while k != i + 1:
			c += 1
			k = l[k - 1]
		print(c, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [-1] * n
	for q in range(n):
		s = []
		q1 = q
		while (len(s) == 0 or q1 != s[0]) and ans[q1] == -1:
			s.append(q1)
			q1 = a[q1] - 1
		if len(s) and s[0] == q1:
			for q2 in range(len(s) - 1, -1, -1):
				ans[s[q2]] = len(s)
		else:
			for q2 in range(len(s) - 1, -1, -1):
				ans[s[q2]] = ans[q1] + len(s) - q2
	print(*ans)


q = int(input())
ans = []
for _ in range(q):
	n = int(input())
	p = list(map(int, input().split()))
	a = [0] * n
	for i in range(n):
		j = 1
		x = p[i]
		b = []
		if a[i] != 0:
			continue
		while x - 1 != i:
			x = p[x - 1]
			b.append(x - 1)
			j += 1
		for k in range(len(b)):
			a[b[k]] = j
		if j == 1:
			a[i] = 1
	ans.append(a)
for i in range(q):
	results = map(str, ans[i])
	answer = ' '.join(results)
	print(answer)


class DisjointSet:

	def __init__(self, n):
		self.data = [-1 for _ in range(n)]
		self.size = n

	def find(self, index):
		value = self.data[index]
		if value < 0:
			return index
		return self.find(value)

	def union(self, x, y):
		x = self.find(x)
		y = self.find(y)
		if x == y:
			return
		if self.data[x] < self.data[y]:
			self.data[x] += self.data[y]
			self.data[y] = x
		else:
			self.data[y] += self.data[x]
			self.data[x] = y
		self.size -= 1
from collections import Counter
for _ in '0' * int(input()):
	n = int(input())
	ns = list(map(int, input().split()))
	disjoint = DisjointSet(n + 1)
	for x in ns:
		disjoint.union(x, ns[x - 1])
	d = Counter([disjoint.find(x) for x in range(1, n + 1)])
	for i in range(1, n + 1):
		print(d.get(disjoint.find(i)), end=' ')


def solve(n, p):
	sol = [0] * (n + 1)
	pos = list(range(0, n + 1))
	solved = 0
	day = 1
	while solved < n:
		new_pos = [0] * (n + 1)
		idx = 1
		for per in p:
			new_pos[per] = pos[idx]
			if sol[idx] == 0 and new_pos[per] == per:
				solved += 1
				sol[idx] = day
				to_fix = p[idx - 1]
				while to_fix != idx:
					sol[to_fix] = day
					to_fix = p[to_fix - 1]
					solved += 1
				if solved == n:
					break
			idx += 1
		pos = new_pos
		day += 1
	for v in sol[1:]:
		print(v, end=' ')
	print()
queries = int(input())
for i in range(queries):
	n = int(input())
	p = [int(x) for x in input().split()]
	solve(n, p)


t = int(input())
for z in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	c = []
	for i in range(1, n + 1):
		count = 0
		x = i
		j = i - 1
		while True:
			k = a[j]
			if k == x:
				count += 1
				break
			else:
				j = k - 1
				count += 1
		c.append(count)
	print(*c)


from math import *

def main():
	for _ in range(int(input())):
		n = int(input())
		arr = [int(x) for x in input().split()]
		for i in range(n):
			f = 0
			e = i - 0
			d = 0
			while not f:
				e = arr[e] - 1
				d += 1
				if e == i:
					f = 1
			print(d, end=' ')
		print()
main()


for case in range(int(input())):
	n = int(input())
	p = list(input().split())
	for i in range(n):
		p[i] = int(p[i])
	p.insert(0, 0)
	use = [False for i in range(n + 1)]
	c = [1 for i in range(n + 1)]
	for i in range(1, n + 1):
		q = p[i]
		tmp = []
		if not use[q]:
			while q != i:
				use[q] = True
				tmp.append(q)
				q = p[q]
			for i in tmp:
				c[i] = len(tmp) + 1
	ans = ''
	for i in range(1, n + 1):
		ans += str(c[i]) + ' '
	print(ans)


N = []
AA = []
t = int(input())
for i in range(t):
	N.append(int(input()))
	a = list(map(int, input().split()))
	for j in range(len(a)):
		a[j] -= 1
	AA.append(a)
for i in range(t):
	n = N[i]
	A = AA[i]
	ans = [0] * n
	for j in range(n):
		c = 1
		b = A[j]
		while b != j:
			b = A[b]
			c += 1
		ans[j] = c
	print(' '.join([str(i) for i in ans]))


import sys, math, string, bisect
input = sys.stdin.readline
from collections import deque, defaultdict
L = lambda : list(map(int, input().split()))
Ls = lambda : list(input().split())
M = lambda : map(int, input().split())
I = lambda : int(input())
n = int(input())
for _ in range(n):
	k = I()
	g = []
	l = [0] + L()
	for i in range(1, k + 1):
		s = i
		c = 1
		while l[s] != i:
			s = l[s]
			c += 1
		g.append(c)
	print(*g)


for _ in range(int(input())):
	n = int(input())
	l = [0] + list(map(int, input().split()))
	for i in range(1, n + 1):
		a = 0
		p = l[i]
		while i != p:
			a += 1
			p = l[p]
		print(a + 1, end=' ')
	print()


q = int(input())
for i in range(q):
	n = int(input())
	p = list(map(int, input().split()))
	a = [0] * n
	for j in range(n):
		if a[j] == 0:
			if p[j] == j + 1:
				a[j] = 1
			else:
				t = p[j]
				d = 1
				b = []
				while t != j + 1:
					b.append(t)
					t = p[t - 1]
					d += 1
				for k in b:
					a[k - 1] = d
				a[j] = d
	print(*a)


def res(i, l):
	s = l[i]
	c = 1
	while s != i:
		s = l[s]
		c += 1
	return c
for _ in range(int(input())):
	input()
	l = [int(i) - 1 for i in input().split()]
	for i in l:
		print(res(i, l))


import sys
input = sys.stdin.readline
q = int(input())
for _ in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [0] * n
	for i in range(n):
		if ans[i]:
			continue
		x = a[i] - 1
		c = 1
		l = [i, x]
		while not i == x:
			x = a[x] - 1
			c += 1
			l.append(x)
		for j in l:
			ans[j] = c
	print(*ans)


q = int(input())
for _ in range(q):
	n = int(input())
	lst = [int(x) - 1 for x in input().split()]
	ans = [0 for i in lst]
	for i in range(len(lst)):
		if ans[i] != 0:
			continue
		(pact, l) = (lst[i], 1)
		while pact != i:
			l += 1
			pact = lst[pact]
		while ans[pact] != l:
			ans[pact] = l
			pact = lst[pact]
	for j in ans:
		print(j, end=' ')
	print('')


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	l = [0] + l
	for i in range(1, n + 1):
		pr = l[i]
		k = 1
		while pr != i:
			pr = l[pr]
			k += 1
		print(k, end=' ')
	print()


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
mod = 10 ** 9 + 7

def lcm(x, y):
	return x * y / gcd(x, y)

def fact(x, mod=mod):
	ans = 1
	for i in range(1, x + 1):
		ans = ans * i % mod
	return ans

def arr2D(n, m, default=0):
	return [[default for j in range(m)] for i in range(n)]

def arr3D(n, m, r, default=0):
	return [[[default for k in range(r)] for j in range(m)] for i in range(n)]

def sortDictV(x):
	return {k: v for (k, v) in sorted(x.items(), key=lambda item: item[1])}

class DSU:

	def __init__(self, length):
		self.length = length
		self.parent = [-1] * self.length

	def getParent(self, node, start):
		if node >= self.length:
			return False
		if self.parent[node] < 0:
			if start != node:
				self.parent[start] = node
			return node
		return self.getParent(self.parent[node], start)

	def union(self, node1, node2):
		parent1 = self.getParent(node1, node1)
		parent2 = self.getParent(node2, node2)
		if parent1 == parent2:
			return False
		elif self.parent[parent1] <= self.parent[parent2]:
			self.parent[parent1] += self.parent[parent2]
			self.parent[parent2] = parent1
		else:
			self.parent[parent2] += self.parent[parent1]
			self.parent[parent1] = parent2
		return True

	def getCount(self, node):
		return -self.parent[self.getParent(node, node)]

def solve(n, lst):
	dsu = DSU(n)
	for i in range(n):
		dsu.union(i, lst[i] - 1)
	for i in lst:
		print(dsu.getCount(i - 1), end=' ')
for _ in range(int(input())):
	n = int(input())
	lst = list(map(int, input().split()))
	solve(n, lst)
	print()


from sys import stdin, stdout
import bisect
import math

def st():
	return list(stdin.readline().strip())

def inp():
	return int(stdin.readline())

def li():
	return list(map(int, stdin.readline().split()))

def mp():
	return map(int, stdin.readline().split())

def pr(n):
	stdout.write(str(n) + '\n')

def soe(limit):
	l = [1] * (limit + 1)
	prime = []
	for i in range(2, limit + 1):
		if l[i]:
			for j in range(i * i, limit + 1, i):
				l[j] = 0
	for i in range(2, limit + 1):
		if l[i]:
			prime.append(i)
	return prime

def segsoe(low, high):
	limit = int(high ** 0.5) + 1
	prime = soe(limit)
	n = high - low + 1
	l = [0] * (n + 1)
	for i in range(len(prime)):
		lowlimit = low // prime[i] * prime[i]
		if lowlimit < low:
			lowlimit += prime[i]
		if lowlimit == prime[i]:
			lowlimit += prime[i]
		for j in range(lowlimit, high + 1, prime[i]):
			l[j - low] = 1
	for i in range(low, high + 1):
		if not l[i - low]:
			if i != 1:
				print(i)

def gcd(a, b):
	while b:
		a = a % b
		(b, a) = (a, b)
	return a

def power(a, n):
	r = 1
	while n:
		if n & 1:
			r = r * a
		a *= a
		n = n >> 1
	return r

def solve():
	n = inp()
	l = li()
	l = [0] + l
	i = 1
	x = []
	for i in range(1, n + 1):
		j = i
		c = 0
		while l[j] != i:
			j = l[j]
			c += 1
		x.append(c + 1)
	print(*x)
for _ in range(inp()):
	solve()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	final = [0] * n
	for i in range(n):
		x = True
		if final[i] == 0:
			k = i
			cnt = 0
			same = []
			while x == True:
				k = a[k] - 1
				cnt += 1
				same.append(k)
				if k == i:
					for j in same:
						final[j] = cnt
					x = False
	print(*final)


q = int(input())
for t in range(q):
	n = int(input())
	l = [int(x) for x in input().split()]
	for i in range(n):
		l[i] -= 1
	days = [0 for i in range(n)]
	used = [False for i in range(n)]
	for i in range(n):
		if used[i] == False:
			curr = []
			pos = i
			while used[pos] == False:
				curr.append(pos)
				used[pos] = True
				pos = l[pos]
			for j in curr:
				days[j] = len(curr)
	for i in days:
		print(i, end=' ')
	print()


n = int(input())
for x in range(n):
	a = int(input())
	array = list(map(int, input().split()))
	empty = []
	dic = {}
	x = 0
	y = 0
	answer = {}
	while True:
		if x >= a:
			break
		if len(answer) == a:
			break
		if array[x] in answer:
			x += 1
		elif array[x] in dic:
			jam = len(empty)
			for it in empty:
				if it in answer:
					pass
				else:
					answer[it] = jam
			empty = []
			y += 1
			x = y
		else:
			dic[array[x]] = 5
			empty.append(array[x])
			x = array[x] - 1
	ham = []
	lam = []
	for it in answer:
		ham.append(it)
	ham.sort()
	for it in ham:
		lam.append(answer[it])
	print(*lam)


def group(d, i, s, visited):
	if visited[i]:
		return s
	while not visited[i]:
		visited[i] = True
		s.append(i)
		i = d[i]
	return s
t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(p) for p in input().split()]
	d = {}
	for i in range(1, n + 1):
		d[i] = arr[i - 1]
	visited = [False] * (n + 1)
	dsu = []
	for i in range(1, n + 1):
		s = []
		if not visited[i]:
			group(d, i, s, visited)
			dsu.append(s)
	print
	days = [0] * (n + 1)
	for i in range(len(dsu)):
		for j in dsu[i]:
			days[j] = len(dsu[i])
	days.pop(0)
	print(*days)


from sys import stdin
from math import *

def c(ar, v, i, count, s):
	while i <= len(ar):
		if v[i] == s:
			return count
		else:
			v[i] = s
			i = ar[i] - 1
			count += 1
for i in range(int(stdin.readline())):
	n = int(stdin.readline())
	ar = list(map(int, stdin.readline().split()))
	g = [0] * n
	v = [0] * n
	s = [0] * 200001
	for j in range(n):
		if v[j] == 0:
			cy = c(ar, v, ar[j] - 1, 0, j + 1)
			v[j] = j + 1
			s[j] = cy
	for j in range(n):
		g[j] = s[v[j] - 1]
	print(*g)


from sys import stdin

def func(n, arr):
	visit = [True] * n
	d = []
	for i in range(n):
		if visit[i] == True:
			m = arr[i]
			visit[m - 1] = False
			ans = [m]
			while m != i + 1:
				m = arr[m - 1]
				visit[m - 1] = False
				ans.append(m)
			d.append(ans)
			visit[i] = False
		else:
			pass
	final = [0] * n
	for i in range(len(d)):
		x = len(d[i])
		for item in d[i]:
			final[item - 1] = x
	return final
q = int(stdin.readline())
for i in range(q):
	n = int(stdin.readline())
	arr = list(map(int, stdin.readline().split()))
	ans = func(n, arr)
	for i in range(n - 1):
		print(ans[i], end=' ')
	print(ans[-1])


q = int(input())
for i in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [-1] * n
	count = 0
	now = 0
	b = []
	noww = []
	m = 0
	while count != n:
		if ans[now] == -1:
			noww.append(now)
			ans[now] = 1
			now = a[now] - 1
			m = min(m, now)
		else:
			count += len(noww)
			b.append(noww)
			noww = []
			now = m + 1
			m += 1
	b.append(noww)
	for elem in b:
		for el in elem:
			ans[el] = len(elem)
	for elem in ans:
		print(elem, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	p.insert(0, 0)
	q = [1] * (n + 1)
	d = {}
	per = []
	l = 0
	for x in p[1:]:
		if q[x]:
			per.append([])
			while q[x]:
				per[-1].append(x)
				d[x] = l
				q[x] = 0
				x = p[x]
			l += 1
	for x in d:
		d[x] = len(per[d[x]])
	for x in p[1:]:
		print(d[x], end=' ')
	print()


case = int(input())
for _ in range(case):
	n = int(input())
	p = list(map(int, input().split()))
	d = dict()
	for i in range(1, n + 1):
		if i in d:
			continue
		tmp = set()
		tmp.add(i)
		t = i
		cnt = 1
		while i != p[t - 1]:
			cnt += 1
			t = p[t - 1]
			tmp.add(t)
		for t in tmp:
			d[t] = cnt
	for i in range(1, n + 1):
		print(d[i], end=' ')


n = int(input())
for i in range(n):
	k = int(input())
	A = list(map(int, input().split()))
	B = [0] * k
	for j in range(k):
		if A[j] == j + 1:
			B[j] = 1
		elif B[j] == 0:
			a = A[j]
			C = []
			C.append(a)
			while a != j + 1:
				a = A[a - 1]
				C.append(a)
				l = len(C)
			for m in range(l):
				B[C[m] - 1] = l
	for q in range(k):
		print(B[q], end=' ')
	print()


q = int(input())
for i in range(q):
	n = int(input())
	l = list(map(int, input().split()))
	l = [0] + l
	ans = [0] * (n + 1)
	for i in range(1, len(l)):
		if l[i] == i:
			ans[i] = 1
		else:
			c = 1
			x = l[i]
			while 1:
				y = l[x]
				x = y
				if y == i:
					ans[i] = c + 1
					break
				else:
					c += 1
	ans = ans[1:]
	print(*ans)


from sys import stdin, stdout
from bisect import bisect_right, bisect_left
from math import gcd
n = int(stdin.readline())
for i in range(n):
	a = int(stdin.readline())
	giv = [0] + [int(i) for i in stdin.readline().split()]
	lst = [1 for i in range(a + 1)]
	ans = ['1' for i in range(a)]
	k = 1
	for j in range(1, len(lst)):
		if lst[j] == 1:
			indx = k
			up = [indx]
			p = giv[indx]
			while p != k:
				up += [indx]
				indx = giv[indx]
				p = giv[indx]
			for q in up:
				ans[q - 1] = str(len(up))
				lst[q] = 0
		k += 1
	out = ' '.join(ans)
	stdout.write(out + '\n')


def add_unless(start, arr, visited, path):
	saved = start
	while True:
		start = arr[start]
		if start == saved:
			break
		visited[start] = True
		path.append(start)
t = int(input())
for i in range(t):
	n = int(input())
	x = [0] + list(map(int, input().split()))
	paths = []
	visited = len(x) * [False]
	for i in range(1, len(x)):
		path = []
		if visited[i]:
			continue
		else:
			path.append(i)
			start = i
			visited[i] = True
			add_unless(start, x, visited, path)
			paths.append(path)
	ans = {}
	for current_path in paths:
		for node in current_path:
			ans[node] = len(current_path)
	val = []
	for j in sorted(list(ans.keys())):
		val.append(ans[j])
	print(*val)


for _ in range(int(input())):
	n = int(input())
	lb = (*map(int, input().split()),)
	for i in range(n):
		(k, c) = (lb[i] - 1, 1)
		while k != i:
			k = lb[k] - 1
			c += 1
		print(c, end=' ')
	print()


q = int(input())
for _ in range(q):
	j = 0
	n = int(input())
	a = [int(i) for i in input().split()]
	answer = [0 for i in range(n)]
	b = [0 for i in range(n)]
	for i in range(n):
		cycle = []
		if not b[i]:
			j = i
		while not b[j]:
			cycle.append(a[j] - 1)
			b[j] = 1
			j = a[j] - 1
		s = len(cycle)
		for k in cycle:
			answer[k] = s
	print(*answer)


def fill(i, a, rec):
	p = 1
	j = a[i] - 1
	temp = [i]
	while j != i:
		p += 1
		temp.append(j)
		j = a[j] - 1
	for i in temp:
		rec[i] = p
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [-1 for i in range(n)]
	for i in range(n):
		if ans[i] == -1:
			fill(i, a, ans)
	for i in ans:
		print(i, end=' ')
	print('')


q = int(input())
for i in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	ans = []
	for j in range(n):
		count = 1
		k = j
		while a[k] != j + 1:
			if a[k] == j + 1:
				break
			count += 1
			k = a[k] - 1
		ans.append(count)
	print(*ans)


import math

def gcd(a, b):
	return a if b == 0 else gcd(b, a % b)

def lcd(a, b):
	return a * b // gcd(a, b)

def input_int():
	return list(map(int, input().split()))

def solve():
	[n] = input_int()
	a = [-1] + input_int()
	res = [-1 for i in range(0, n + 1)]
	for i in range(1, n + 1):
		if res[i] != -1:
			continue
		j = a[i]
		c = 1
		while j != i:
			c += 1
			j = a[j]
		j = a[i]
		res[i] = c
		while j != i:
			res[j] = c
			j = a[j]
	print(' '.join(list(map(str, res[1:]))))
	return
[q] = input_int()
for _ in range(0, q):
	solve()


q = int(input())
for qwe in range(q):
	n = int(input())
	s = list(map(int, input().split()))
	rez = []
	for i in range(n):
		rez.append(0)
	z = n
	f = True
	nach = 0
	while z != 0:
		mas = []
		iter = nach
		while iter < n:
			if rez[nach] != 0:
				nach += 1
				iter += 1
				continue
			if s[iter] == nach + 1:
				mas.append(iter)
				break
			else:
				mas.append(iter)
				iter = s[iter] - 1
		for i in range(len(mas)):
			rez[mas[i]] = len(mas)
		z -= len(mas)
		nach += 1
	for i in rez:
		print(i, end=' ')
	print()


for i in range(int(input())):
	n = int(input())
	books = list(map(int, input().split()))
	ans = []
	i = 1
	while len(ans) != n:
		t = books[i - 1]
		count = 1
		while t != i:
			t = books[t - 1]
			count = count + 1
		ans.append(count)
		i = i + 1
	print(*ans)


for _ in range(int(input())):
	q = int(input())
	a = list(map(int, input().split()))
	a.insert(0, 0)
	a = [[i, 1] for i in a]
	l = [0] * (q + 1)
	for i in range(1, q + 1):
		count = 1
		p = i
		if a[i][1] == 1:
			t = [i]
			while True:
				if i == a[p][0]:
					for j in t:
						l[j] = count
						a[j][1] = 0
					break
				p = a[p][0]
				count += 1
				t.append(p)
	print(*l[1:])


import math
import sys
t = int(sys.stdin.readline())
for _ in range(t):
	n = int(sys.stdin.readline())
	l = list(map(int, input().split()))
	visited = [0] * n
	for i in range(n):
		l[i] -= 1
	ans = [0] * n
	for i in range(n):
		if visited[i] == 0:
			cur = []
			while visited[i] == 0:
				cur.append(i)
				visited[i] = 1
				i = l[i]
			for i in cur:
				ans[i] = len(cur)
	print(*ans)


for x in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	m = []
	for i in range(n):
		k = i
		p = 1
		while a[k] != i + 1:
			p += 1
			k = a[k] - 1
		m.append(p)
	print(*m)


def dfs(i, res, lst):
	j = lst[i] - 1
	(length, setting) = (1, [i])
	while j != i:
		length += 1
		setting.append(j)
		j = lst[j] - 1
	for (i, x) in enumerate(setting):
		res[x] = length
for _ in range(int(input())):
	n = int(input())
	lst = list(map(int, input().split()))
	res = [0] * n
	for (i, x) in enumerate(lst):
		if res[i] == 0:
			dfs(i, res, lst)
	print(*res)


for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	ans = [0 for i in range(n)]
	for i in range(n):
		if ans[i] != 0:
			continue
		cycle = []
		cycle.append(i)
		pos = p[i] - 1
		flag = 1
		while pos != i:
			cycle.append(pos)
			pos = p[pos] - 1
			flag += 1
		for k in cycle:
			ans[k] = flag
	print(*ans)


q = int(input())
queries = []
for i in range(q):
	n = int(input())
	vals = input().split()
	query = [int(val) for val in vals]
	queries.append(query)
for permuation in queries:
	n = len(permuation)
	results = [None] * n
	for i in range(n):
		if results[i] is None:
			group = {i}
			nxt = permuation[i] - 1
			count = 1
			while nxt != i:
				group.add(nxt)
				nxt = permuation[nxt] - 1
				count += 1
			for member in group:
				results[member] = str(count)
	print(' '.join(results))


t = int(input())
for w in range(t):
	n = int(input())
	l = [int(i) for i in input().split()]
	a = [0] * n
	l1 = [0] * n
	for i in range(n):
		l2 = []
		c = 0
		if l1[i] == 0:
			j = i
			while l1[j] == 0:
				l1[j] = 1
				l2.append(j)
				j = l[j] - 1
				c += 1
			for j in l2:
				a[j] = c
	print(*a)


import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
mod = 10 ** 9 + 7

def lcm(x, y):
	return x * y / gcd(x, y)

def fact(x, mod=mod):
	ans = 1
	for i in range(1, x + 1):
		ans = ans * i % mod
	return ans

def arr2D(n, m, default=0):
	return [[default for j in range(m)] for i in range(n)]

def arr3D(n, m, r, default=0):
	return [[[default for k in range(r)] for j in range(m)] for i in range(n)]

def sortDictV(x):
	return {k: v for (k, v) in sorted(x.items(), key=lambda item: item[1])}
exec('\nclass DSU:\n    def __init__(self, length): self.length = length; self.parent = [-1] * self.length  # O(log(n))\n    def getParent(self, node, start):  # O(log(n))\n        if node >= self.length: return False\n        if self.parent[node] < 0:\n            if start != node: self.parent[start] = node\n            return node\n        return self.getParent(self.parent[node], start)\n    def union(self, node1, node2):  # O(log(n))\n        parent1 = self.getParent(node1, node1); parent2 = self.getParent(node2, node2)\n        if parent1 == parent2: return False\n        elif self.parent[parent1] <= self.parent[parent2]: self.parent[parent1] += self.parent[parent2]; self.parent[parent2] = parent1\n        else: self.parent[parent2] += self.parent[parent1]; self.parent[parent1] = parent2\n        return True\n    def getCount(self, node):  return -self.parent[self.getParent(node, node)] # O(log(n))\n')

def solve(n, lst):
	dsu = DSU(n)
	for i in range(n):
		dsu.union(i, lst[i] - 1)
	for i in lst:
		print(dsu.getCount(i - 1), end=' ')
for _ in range(int(input())):
	n = int(input())
	lst = list(map(int, input().split()))
	solve(n, lst)
	print()


class UnionFind:

	def __init__(self, n):
		self.n = n
		self.root = [-1] * (n + 1)
		self.rnk = [0] * (n + 1)

	def Find_Root(self, x):
		if self.root[x] < 0:
			return x
		else:
			self.root[x] = self.Find_Root(self.root[x])
			return self.root[x]

	def Unite(self, x, y):
		x = self.Find_Root(x)
		y = self.Find_Root(y)
		if x == y:
			return
		elif self.rnk[x] > self.rnk[y]:
			self.root[x] += self.root[y]
			self.root[y] = x
		else:
			self.root[y] += self.root[x]
			self.root[x] = y
			if self.rnk[x] == self.rnk[y]:
				self.rnk[y] += 1

	def isSameGroup(self, x, y):
		return self.Find_Root(x) == self.Find_Root(y)

	def Count(self, x):
		return -self.root[self.Find_Root(x)]
import sys
input = sys.stdin.readline
Q = int(input())
Query = []
for _ in range(Q):
	N = int(input())
	A = list(map(int, input().split()))
	Query.append((N, A))
for (N, A) in Query:
	uf = UnionFind(N + 1)
	for (i, a) in enumerate(A):
		uf.Unite(i + 1, a)
	ans = []
	for n in range(1, N + 1):
		ans.append(uf.Count(n))
	print(*ans)


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	a = list(map(int, input().split()))
	for i in range(n):
		a[i] -= 1
	res = [0 for _ in range(n)]
	for i in range(n):
		if res[i] != 0:
			continue
		x = [i]
		j = a[i]
		ans = 1
		while j != i:
			j = a[j]
			ans += 1
			x.append(j)
		for k in x:
			res[k] = ans
	print(*res)


q = int(input())
for _ in range(q):
	n = int(input())
	A = [int(x) - 1 for x in input().split()]
	B = [-1] * n
	for i in range(n):
		if B[i] == -1:
			C = set()
			while i not in C:
				C.add(i)
				i = A[i]
			for x in C:
				B[x] = len(C)
	print(' '.join(map(str, B)))


def f(k):
	global ans
	used[k] = 1
	ans += 1
	if used[a[k] - 1] == 1:
		return
	c[a[k] - 1] = c[k]
	f(a[k] - 1)
q = int(input())
for u in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	c = [0] * n
	b = []
	j = 0
	used = [0] * n
	for i in range(n):
		ans = 0
		if used[i] == 0:
			c[i] = j
			j += 1
			f(i)
			b.append(ans)
	for i in range(n):
		print(b[c[i]], end=' ')
	print()


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ass = []
	for i in range(len(a)):
		ans = 1
		pos = a[i]
		while pos != i + 1:
			ans += 1
			pos = a[pos - 1]
		ass.append(ans)
	print(*ass)


def return_books():
	ans = []
	for i in range(n):
		curr_day = 1
		curr_child = arr[i] - 1
		while curr_child != i:
			curr_child = arr[curr_child] - 1
			curr_day += 1
		ans.append(curr_day)
	return ans
q = int(input())
for _ in range(q):
	n = int(input())
	arr = list(map(int, input().split()))
	print(*return_books())


q = int(input())
lst = []
for query in range(q):
	input().strip()
	lst += [list(map(int, input().strip().split(' ')))]
for query in range(len(lst)):
	cur_list = lst[query]
	times = [1] * len(lst[query])
	for list_pos in range(len(lst[query])):
		original_value = cur_list[list_pos]
		value = cur_list[original_value - 1]
		while value != original_value:
			value = cur_list[value - 1]
			times[list_pos] += 1
	print(' '.join(list(map(str, times))))


q = int(input())
for i in range(q):
	n = int(input())
	p = list(map(int, input().split()))
	memo = [-1 for k in range(n + 1)]
	chain = []

	def traverse(org, s):
		global chain
		if org == p[s - 1]:
			return 1
		chain.append(s)
		return traverse(org, p[s - 1]) + 1
	for j in p:
		if memo[j] != -1:
			print(memo[j], end=' ')
			continue
		chain = []
		r = traverse(j, j)
		for k in chain:
			memo[k] = r
		print(r, end=' ')
	print('')


from collections import deque
from math import ceil, floor, sqrt, gcd

def ii():
	return int(input())

def mi():
	return map(int, input().split())

def li():
	return list(mi())

def si():
	return input()
t = ii()
while t:
	t -= 1
	n = ii()
	a = li()
	res = [0] * (n + 1)
	for i in range(1, n + 1):
		if res[i] != 0:
			continue
		pos = a[i - 1]
		b = [i]
		while pos != i:
			b.append(pos)
			pos = a[pos - 1]
		for j in b:
			res[j] = len(b)
	print(*res[1:])


q = int(input())
while q > 0:
	n = int(input())
	arr = [int(x) for x in input().split()]
	vis = [False] * n
	res = [0] * n
	for i in range(n):
		if vis[i]:
			continue
		temp = arr[i]
		s = set([temp])
		c = 0
		while True:
			temp = arr[temp - 1]
			s.add(temp)
			c += 1
			if arr[i] == temp:
				break
		for a in s:
			vis[a - 1] = True
			res[a - 1] = c
	print(*res)
	q -= 1


def f(i):
	global j
	if r[i] < 1:
		r[i] = 1
		j += 1
		f(a[i] - 1)
		r[i] = j
I = input
for _ in [0] * int(I()):
	n = int(I())
	a = (*map(int, I().split()),)
	r = [0] * n
	while n:
		n -= 1
		j = 0
		f(n)
	print(*r)


tc = int(input())
for _ in range(tc):
	n = int(input())
	nums = list(map(int, input().split()))
	temp = nums[:]
	temp2 = nums[:]
	ans = [0] * n
	anscnt = 0
	cnt = 1
	while anscnt != n:
		for (i, num) in enumerate(nums):
			temp2[num - 1] = temp[i]
			if temp2[num - 1] == nums[num - 1] and ans[num - 1] == 0:
				ans[num - 1] = cnt
				anscnt += 1
		temp = temp2[:]
		cnt += 1
	print(*ans)


q = int(input())
queries = []
for i in range(q):
	n = int(input())
	items = input().split()
	p = [int(item) for item in items]
	queries.append(p)
for query in queries:
	n = len(query)
	results = [None] * n
	for i in range(n):
		if results[i] is None:
			group = {i}
			nxt = query[i] - 1
			count = 1
			while nxt != i:
				group.add(nxt)
				nxt = query[nxt] - 1
				count += 1
			for member in group:
				results[member] = str(count)
	print(' '.join(results))


def solve():
	n = int(input())
	a = list(map(lambda x: x - 1, map(int, input().split())))
	ans = [-1 for _ in range(n)]
	for i in range(n):
		if ans[i] != -1:
			continue
		now = i
		cycle = []
		while ans[now] == -1:
			ans[now] = 0
			cycle.append(now)
			now = a[now]
		sz = len(cycle)
		for j in cycle:
			ans[j] = sz
	return ' '.join(map(str, ans))

def main():
	q = int(input())
	for _ in range(q):
		print(solve())
main()


import time
import string
LOCAL = False
start_time = None
if LOCAL:
	start_time = time.time()
b = int(input())
while b:
	b -= 1
	n = int(input())
	ais = list(map(lambda x: int(x), input().split(' ')))
	checked = [False for _ in range(n)]
	sets = []
	pos = {}
	for (i, v) in enumerate(ais):
		if not checked[i]:
			checked[i] = True
			q = ais[v - 1]
			new_set = {v, q}
			while q != v:
				q = ais[q - 1]
				checked[q - 1] = True
				new_set.add(q)
			lset = len(new_set)
			for j in new_set:
				pos[j] = lset
	print(' '.join([str(pos[i]) for i in sorted(pos.keys())]))
if LOCAL:
	print('--- %s seconds ---' % (time.time() - start_time))


from sys import stdin, stdout
t = int(stdin.readline())
while t > 0:
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	from collections import defaultdict
	adj = defaultdict(list)
	for i in range(n):
		(x, y) = (i + 1, a[i])
		adj[x].append(y)
		adj[y].append(x)

	def dfs(n, adj, vis):
		vis.add(n)
		for node in adj[n]:
			if node not in vis:
				return 1 + dfs(node, adj, vis)
		return 0
	ans = []
	for i in range(n):
		vis = set()
		c = dfs(i + 1, adj, vis)
		ans.append(c + 1)
	for i in range(len(ans)):
		stdout.write('{} '.format(ans[i]))
	stdout.write('\n')
	t -= 1


import sys, math, itertools
from collections import Counter, deque, defaultdict
from bisect import bisect_left, bisect_right
from heapq import heappop, heappush, heapify, nlargest
from copy import deepcopy
mod = 10 ** 9 + 7
INF = float('inf')

def inp():
	return int(sys.stdin.readline())

def inpl():
	return list(map(int, sys.stdin.readline().split()))

def inpl_1():
	return list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))

def inps():
	return sys.stdin.readline()

def inpsl(x):
	tmp = sys.stdin.readline()
	return list(tmp[:x])

def err(x):
	print(x)
	exit()
for _ in range(inp()):
	n = inp()
	a = inpl_1()
	res = [-1] * n
	seen = [0] * n
	for i in range(n):
		if seen[i]:
			continue
		roop = [i]
		now = a[i]
		while now != i:
			roop.append(now)
			now = a[now]
		ans = len(roop)
		for x in roop:
			res[x] = ans
	print(*res)


from collections import Counter
from collections import defaultdict
import math
t = int(input())
for _ in range(0, t):
	n = int(input())
	a = list(map(int, input().split()))
	d1 = defaultdict(lambda : -1)
	for i in range(0, n):
		if d1[i + 1] != -1:
			print(d1[i + 1], end=' ')
			continue
		l = list()
		c = i + 1
		d = a[i]
		l.append(d)
		ans = 1
		while d != c:
			d = a[d - 1]
			l.append(d)
			ans = ans + 1
		for k in l:
			d1[k] = ans
		print(d1[k], end=' ')
	else:
		print()


def solution(A):
	n = len(A)
	ar = [-1] * n
	for k in range(n):
		if ar[k] == -1:
			temp = A[k]
			loc_ans = 1
			while temp != k:
				temp = A[temp]
				loc_ans += 1
			ar[k] = loc_ans
			temp = A[k]
			while temp != k:
				ar[temp] = ar[k]
				temp = A[temp]
	for k in ar:
		print(k, end=' ')
	print()
for k in range(int(input())):
	n = int(input())
	A = [int(x) - 1 for x in input().split()]
	solution(A)


for _ in range(int(input())):
	n = int(input())
	s = list(map(int, input().split()))
	k = [0]
	for i in range(n):
		k.append(s[i])
	s = k[:]
	res = {}
	for i in s:
		res[i] = 1
	for i in range(n):
		if res[i] == 1:
			pos = s[i]
			ans = 1
			j = i
			cycle = [i]
			while pos != j:
				cycle.append(pos)
				ans += 1
				pos = s[pos]
			for el in cycle:
				res[el] = ans
	ans = []
	for i in res:
		if i != 0:
			ans.append(res[i])
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	x = [0] * n
	for i in range(n):
		v = [i]
		if x[i] == 0:
			q = t = a[i]
			p = 1
			while 1:
				if a[t - 1] != q:
					p += 1
					v.append(t - 1)
					t = a[t - 1]
				else:
					for i in v:
						x[i] = p
					break
		else:
			continue
	print(*x)


from sys import stdin, stdout
t = int(stdin.readline())

def getRoot(i, par):
	while i != par[i]:
		i = par[i]
	return i

def find(a, b, par):
	return getRoot(a, par) == getRoot(b, par)

def doUnion(a, b, par, size):
	if find(a, b, par):
		return False
	r1 = getRoot(a, par)
	r2 = getRoot(b, par)
	s1 = size[r1]
	s2 = size[r2]
	if s1 > s2:
		par[r2] = r1
		size[r1] += s2
	else:
		par[r1] = r2
		size[r2] += s1
	return True
while t > 0:
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	(par, size) = ([i for i in range(n + 1)], [1 for i in range(n + 1)])
	for i in range(n):
		(x, y) = (i + 1, a[i])
		doUnion(x, y, par, size)
	ans = []
	for i in range(n):
		c = size[getRoot(i + 1, par)]
		ans.append(c)
	for i in range(len(ans)):
		stdout.write('{} '.format(ans[i]))
	stdout.write('\n')
	t -= 1


import sys
from collections import deque, defaultdict
from fractions import gcd
from math import ceil

class UnionFind:

	def __init__(self, n):
		self.n = n
		self.root = [-1] * (n + 1)
		self.rnk = [0] * (n + 1)

	def Find_Root(self, x):
		if self.root[x] < 0:
			return x
		else:
			self.root[x] = self.Find_Root(self.root[x])
			return self.root[x]

	def Unite(self, x, y):
		x = self.Find_Root(x)
		y = self.Find_Root(y)
		if x == y:
			return
		elif self.rnk[x] > self.rnk[y]:
			self.root[x] += self.root[y]
			self.root[y] = x
		else:
			self.root[y] += self.root[x]
			self.root[x] = y
			if self.rnk[x] == self.rnk[y]:
				self.rnk[y] += 1

	def isSameGroup(self, x, y):
		return self.Find_Root(x) == self.Find_Root(y)

	def Count(self, x):
		return -self.root[self.Find_Root(x)]

def N():
	return int(sys.stdin.readline())

def NK():
	return map(int, sys.stdin.readline().split())

def LS_I():
	return [int(x) for x in sys.stdin.readline().split()]

def LS_S():
	return list(input())

def main():
	q = N()
	for _ in range(q):
		n = N()
		ls = LS_I()
		uni = UnionFind(n)
		for i in range(n):
			now = ls[i]
			uni.Unite(now, i + 1)
		for i in range(1, n + 1):
			print(uni.Count(i), end=' ')
		print()
main()


from collections import defaultdict
from collections import Counter
import math
import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def listt():
	return [int(i) for i in input().split()]

def gcd(a, b):
	return math.gcd(a, b)

def lcm(a, b):
	return a * b // gcd(a, b)

def factors(n):
	step = 2 if n % 2 else 1
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(math.sqrt(n)) + 1, step) if n % i == 0)))

def comb(n, k):
	factn = math.factorial(n)
	factk = math.factorial(k)
	fact = math.factorial(n - k)
	ans = factn // (factk * fact)
	return ans

def is_prime(n):
	if n <= 1:
		return False
	if n == 2:
		return True
	if n > 2 and n % 2 == 0:
		return False
	max_div = math.floor(math.sqrt(n))
	for i in range(3, 1 + max_div, 2):
		if n % i == 0:
			return False
	return True

def maxpower(n, x):
	B_max = int(math.log(n, x)) + 1
	return B_max

def binaryToDecimal(n):
	return int(n, 2)
t = int(input())
for _ in range(t):
	n = int(input())
	l = listt()
	li = []
	for i in range(n):
		ans = l[i]
		c = 1
		while ans != i + 1:
			ans = l[ans - 1]
			c += 1
		li.append(c)
	print(*li)


q = int(input())
for i in range(q):
	n = int(input())
	A = [i + 1 for i in range(n)]
	B = list(map(int, input().split()))
	C = []
	D = [0] * n
	k = 0
	l = 0
	while k != n:
		l += 1
		for j in range(n):
			h = A[B[j] - 1]
			C.append(h)
			if h == j + 1 and D[j] == 0:
				D[j] = l
				k += 1
		A = C
		C = []
	print(*D)


for i in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	ans = [0] * n
	for i in p:
		if ans[i - 1]:
			continue
		s = set()
		s.add(i)
		x = p[i - 1]
		while x != i:
			s.add(x)
			x = p[x - 1]
		for i in s:
			ans[i - 1] = len(s)
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	A = list(map(int, input().split()))
	B = [0] * n
	for i in range(n):
		if not B[i]:
			x = A[i] - 1
			C = {i, x}
			while x != i:
				x = A[x] - 1
				C.add(x)
			for c in C:
				B[c] = len(C)
	print(*B)


def krug(j, b):
	while True:
		if j in b:
			return
		b.append(j)
		j = ar[j]
q = int(input())
for i in range(q):
	n = int(input())
	c = [0] * n
	ar = [int(s) - 1 for s in input().split()]
	for j in range(n):
		b = []
		if c[j] == 0:
			krug(j, b)
		for j in range(len(b)):
			c[b[j]] = len(b)
	print(*c)


import sys
from collections import Counter
input = lambda : sys.stdin.readline().rstrip('\r\n')

class DSU(object):

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.rank = [1] * n
		self.cycle = False

	def find(self, key):
		if self.parent[key] != key:
			self.parent[key] = self.find(self.parent[key])
		return self.parent[key]

	def union(self, a, b):
		(s1, s2) = (self.find(a), self.find(b))
		if s1 != s2:
			if self.rank[s1] < self.rank[s2]:
				self.parent[s1] = s2
				self.rank[s2] += self.rank[s1]
			else:
				self.parent[s2] = s1
				self.rank[s1] += self.rank[s2]
		else:
			self.cycle = True

	def has_cycle(self):
		return self.cycle

	def show_parent(self):
		return self.parent

	def show_rank(self):
		return self.rank

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	d = DSU(n + 1)
	for i in range(n):
		d.union(i + 1, a[i])
	leader = d.show_parent()[1:]
	rank = d.show_rank()[1:]
	ans = []
	for i in range(n):
		ans.append(rank[d.find(a[i]) - 1])
	print(*ans)
for _ in range(int(input())):
	solve()


q = int(input())
for i in range(q):
	n = int(input())
	test = [-1] * n
	arr = [-1] * n
	p = [int(x) for x in input().split()]
	counter = 0
	i = 0
	for i in range(n):
		if test[i] == -1:
			counter = 0
			while 1:
				if test[i] != -1:
					arr[i] = counter - test[i]
					cycle = arr[i]
					j = i
					while 1:
						arr[j] = cycle
						j = p[j] - 1
						if j == i:
							break
					break
				test[i] = counter
				counter += 1
				i = p[i] - 1
	print(*arr)


n = int(input())
for i in range(0, n):
	o = int(input())
	p = input().rstrip().split(' ')
	for j in range(0, len(p)):
		A = j + 1
		ans = int(p[j])
		cnt = 1
		while 1:
			if ans != A:
				cnt += 1
				B = int(p[ans - 1])
				ans = B
			else:
				break
		print(cnt, end=' ')
	print()


def solve(n, p):
	ans = [0] * n
	for i in range(1, n + 1):
		if ans[i - 1] == 0:
			cycle = [i]
			pos = p[i - 1]
			while pos != i:
				cycle.append(pos)
				pos = p[pos - 1]
			l = len(cycle)
			for i in cycle:
				ans[i - 1] = l
		else:
			pass
	return ' '.join((str(i) for i in ans))
for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	print(solve(n, p))


import copy
import sys
input = sys.stdin.readline

def main():
	q = int(input())
	for x in range(q):
		nb = int(input())
		tab = list(map(int, input().split()))
		for y in range(nb):
			tab[y] -= 1
		v = [0] * nb
		dist = [0] * nb
		ori = [0] * nb
		for y in range(nb):
			if not v[y]:
				v[y] = 1
				i = tab[y]
				ori[y] = y
				l = 1
				while i != y:
					ori[i] = y
					i = tab[i]
					v[i] = 1
					l += 1
				dist[y] = l
		for x in range(nb):
			print(dist[ori[x]], end=' ')
		print()
main()


t = int(input())
for _ in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	ans = [-1] * n
	for i in range(n):
		if ans[i] != -1:
			continue
		memo = {}
		tmp = i
		memo[tmp] = 1
		cnt = 1
		while True:
			tmp = p[tmp] - 1
			if tmp in memo:
				break
			else:
				memo[tmp] = 1
				cnt += 1
		for j in memo:
			ans[j] = cnt
	print(*ans)


q = int(input())
for _ in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	l = []
	j = 0
	for i in a:
		l.append([i - 1, j])
		j += 1
	mark = [0] * n
	ans = [0] * n
	for i in range(n):
		if mark[i] == 0:
			count = 0
			t = []
			x = l[i][0]
			j = i
			while mark[j] != 1:
				t.append(j)
				mark[j] = 1
				j = l[j][0]
				count += 1
			for x in t:
				ans[x] = count
	print(*ans)


t = int(input())
for x in range(t):
	n = int(input())
	l1 = [int(x) for x in input().split()]
	i = 0
	ans = [0] * n
	visited = []
	while i < len(l1):
		if l1[i] == i + 1:
			ans[i] = 1
			visited.append(i)
		elif i not in visited:
			j = i
			cycle = []
			while j not in visited:
				cycle.append(j)
				visited.append(j)
				j = l1[j] - 1
			for x in cycle:
				ans[x] = len(cycle)
		i += 1
	print(*ans)


tc = int(input())
while tc > 0:
	tc -= 1
	n = int(input())
	p = [0] + [int(j) for j in input().split()]
	ans = [0] * (n + 1)
	mk = [False] * (n + 1)
	for i in range(1, n + 1):
		if not mk[i]:
			sz = 1
			curr = p[i]
			mk[i] = True
			while curr != i:
				sz += 1
				mk[curr] = True
				curr = p[curr]
			ans[i] = sz
			curr = p[i]
			while curr != i:
				ans[curr] = sz
				curr = p[curr]
	print(' '.join([str(x) for x in ans[1:]]))


p = []
f = []

def trace(start_index, next_index, depth):
	if start_index == next_index:
		f[start_index] = depth
		return depth
	total_depth = trace(start_index, p[next_index] - 1, depth + 1)
	f[next_index] = total_depth
	return total_depth
q = int(input())
for i in range(q):
	n = int(input())
	line = input()
	p = line.split(' ')
	p = [int(x) for x in p]
	f = [0] * len(p)
	for index in range(len(p)):
		if f[index] == 0:
			f[index] = trace(index, p[index] - 1, 1)
	s = ' '.join([str(x) for x in f])
	print(s)


T = int(input())
for _ in range(T):
	N = int(input())
	A = [-1] + list(map(int, input().split()))
	v = [-1] + [0 for i in range(N)]
	l = [-1] + [0 for i in range(N)]
	for i in range(1, N + 1):
		if v[i] != 0:
			continue
		j = A[i]
		x = 1
		v[i] = i
		while i != j:
			v[j] = i
			j = A[j]
			x += 1
		l[i] = x
	for i in A[1:]:
		print(l[v[i]], end=' ')
	print()


def solve(arr, n):
	ans = [1] * n
	vis = [False] * n
	for i in range(n):
		if vis[i] == True:
			continue
		count = 0
		c = i
		h = [i]
		vis[i] = True
		while i != arr[c]:
			vis[arr[c]] = True
			h.append(arr[c])
			ind = arr[c]
			c = ind
			count += 1
		for val in h:
			ans[val] += count
	for val in ans:
		print(val, end=' ')
	print('\n', end='')
t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(x) - 1 for x in input().split()]
	solve(arr, n)


def make_set(a):
	parent[a] = a
	size[a] = 1

def find_set(a):
	if parent[a] == a:
		return a
	else:
		parent[a] = find_set(parent[a])
		return parent[a]

def union_sets(a, b):
	a = find_set(a)
	b = find_set(b)
	if a != b:
		if size[a] < size[b]:
			(a, b) = (b, a)
		parent[b] = a
		size[a] += size[b]
q = int(input())
for _ in range(q):
	n = int(input())
	parent = [None for x in range(n)]
	day = [0 for x in range(n)]
	size = [0 for x in range(n)]
	partner = list(map(int, input().split()))
	for i in range(n):
		make_set(partner[i] - 1)
	for i in range(n):
		union_sets(i, partner[i] - 1)
	for i in range(n):
		representative = find_set(partner[i] - 1)
		day[representative] += 1
	for i in range(n):
		representative = find_set(partner[i] - 1)
		print(day[representative], end=' ')
	print()


t = int(input())
for _ in range(t):
	q = int(input())
	l = list(map(int, input().split()))
	ans = [0] * q
	d = {}
	temp = l[:]
	count = 1
	t = 20001
	while t >= 0:
		temp1 = temp[:]
		for j in range(q):
			if temp1[j] == j + 1:
				if ans[j] == 0:
					ans[j] = count
		for j in range(q):
			temp[j] = temp1[l[j] - 1]
		count += 1
		t1 = 0
		for i in range(q):
			if ans[i] != 0:
				t1 += 1
		if t1 == q:
			break
		t -= 1
	print(*ans)


from sys import exit as sys_return

def find_cycles(amount, kids_input):
	result = [0] * (amount + 1)
	for i in range(1, amount + 1):
		if result[i] != 0:
			continue
		size_of_a_cycle = 1
		cycle = [i]
		position = kids_input[i - 1]
		while position != i:
			cycle.append(position)
			position = kids_input[position - 1]
			size_of_a_cycle += 1
		for j in cycle:
			result[j] = size_of_a_cycle
	return result
queries = int(input())
while queries != 0:
	queries -= 1
	amount = int(input())
	kids_unique = find_cycles(amount, list(map(int, input().split())))
	for i in range(1, amount + 1):
		print(kids_unique[i], end=' ')
	print()


import copy
t = int(input())
while t:
	n = int(input())
	l = list(map(int, input().split()))
	l1 = []
	for i in l:
		l1.append(i - 1)
	l = l1
	mainl = copy.deepcopy(l)
	mainn = n
	ansarray = []
	for i in range(n):
		k = l[i]
		count = 1
		while l[k] != mainl[i]:
			k = mainl[k]
			count += 1
		ansarray.append(count)
	for i in ansarray:
		print(i, end=' ')
	print()
	t = t - 1


q = int(input())
for i in range(q):
	n = int(input())
	a = list(map(int, input().split(' ')))
	c = [0 for i in range(n)]
	l = []
	abc = [0 for i in range(n)]
	for i in range(len(a)):
		cnt = 0
		d = a[i]
		l = []
		if c[i] == 0:
			c[i] = 1
			l.append(d)
			while d != i + 1:
				c[d - 1] = 1
				d = a[d - 1]
				l.append(d)
				cnt = cnt + 1
			for i in l:
				abc[i - 1] = cnt + 1
	for i in abc:
		print(i, end=' ')
	print()


q = int(input())
for t in range(q):
	n = int(input())
	l = [int(i) for i in input().split(' ')]
	flag = True
	ans = []
	for i in range(1, len(l) + 1):
		j = l[i - 1]
		count = 1
		while j != i:
			j = l[j - 1]
			count += 1
		ans.append(count)
	for i in ans:
		print(i, end=' ')
	print()


t = int(input())
for z in range(t):
	n = int(input())
	p = [int(x) - 1 for x in input().split()]
	ans = [0] * n
	for i in range(n):
		if ans[i] != 0:
			continue
		cur = i
		next = p[i]
		count = 1
		while cur != next:
			next = p[next]
			count += 1
		ans[cur] = count
		next = p[i]
		while cur != next:
			ans[next] = count
			next = p[next]
	for i in range(n):
		print(ans[i], end=' ')
	print()


def main():
	t = int(input())
	for testcase in range(t):
		n = int(input())
		arr = [int(x) for x in input().split()]
		ans = [0 for _ in range(n)]
		for i in range(n):
			index = i + 1
			if ans[i] != 0:
				continue
			if arr[i] == index:
				ans[i] = 1
			else:
				current = arr[i]
				count = 1
				cycle = [i]
				while current != index:
					current = arr[current - 1]
					count += 1
					cycle.append(current - 1)
				for item in cycle:
					ans[item] = count
		for val in ans:
			print(val, end=' ')
		print()
main()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	c = [0] * n
	b = [True] * n
	for i in range(0, n):
		if a[i] == i + 1 and b[i]:
			c[i] += 1
			b[i] = False
		elif not b[i]:
			continue
		else:
			c[i] += 1
			ind = a[i] - 1
			b[i] = False
			l = []
			while ind != i:
				b[ind] = False
				l.append(ind)
				temp = a[ind] - 1
				ind = temp
				c[i] += 1
			for j in l:
				c[j] = c[i]
	for i in range(0, n):
		print(c[i], end=' ')
	print()


nq = int(input())
iters = 0
while iters < nq:
	iters += 1
	nkids = int(input())
	kids = list(map(int, input().split()))
	idx = 0
	paths = [0] * nkids
	for kid in kids:
		idx = kid - 1
		cost = 0
		if paths[idx]:
			pass
		else:
			days = 1
			path = set([idx])
			while kids[idx] != kid:
				days += 1
				idx = kids[idx] - 1
				path.add(idx)
			for i in path:
				paths[i] = days
	print(' '.join(map(str, paths)))


import sys
input = sys.stdin.readline
q = int(input())
for _ in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	ans = []
	for i in range(n):
		x = a[i]
		c = 1
		while not i + 1 == x:
			x = a[x - 1]
			c += 1
		ans.append(c)
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	arr = [int(i) for i in input().split()]
	dic = {}
	for i in range(1, n + 1):
		dic[i] = arr[i - 1]
	for i in range(1, n + 1):
		s = 0
		j = i
		while dic[j] != i:
			s += 1
			j = dic[j]
		print(s + 1, end=' ')
	print()


import sys
input = sys.stdin.readline

def main():
	q = int(input())
	for _ in range(q):
		n = int(input())
		a = list(map(int, input().split()))
		d = {i + 1: a[i] for i in range(n)}
		ans = [0] * n
		used = set()
		for i in range(n):
			if a[i] in used:
				continue
			else:
				query = a[i]
				carry = {a[i]}
				while query != i + 1:
					query = d[query]
					carry.add(query)
				z = len(carry)
				for k in carry:
					ans[k - 1] = z
					used.add(k)
		print(*ans)
main()


def al(pl, n):
	pl = [0] + pl
	rl = [0] * (n + 1)
	for i in range(1, n + 1):
		if rl[i] > 0:
			continue
		p = i
		uset = [i]
		while pl[p] != i:
			p = pl[p]
			uset.append(p)
		for j in uset:
			rl[j] = len(uset)
	return rl[1:]
q = int(input())
for _ in range(q):
	n = int(input())
	pl = list(map(int, input().split()))
	print(*al(pl, n))


q = int(input())
for _ in range(q):
	n = int(input())
	p = list(map(int, input().strip().split()))
	d = {i + 1: p[i] for i in range(n)}
	l = [0] * n
	for i in range(n):
		j = int(i + 1)
		c = 1
		while i + 1 != d[j]:
			j = d[j]
			c += 1
		l[i] = c
	print(*l)


q = int(input())
for i in range(q):
	n = int(input())
	p = [int(x) for x in input().split()]
	p1 = p.copy()
	cycles = []
	a = [0] * n
	while len(p1):
		p_i = p1[0]
		cycle = []
		end = 1
		while end:
			if p_i not in cycle:
				cycle.append(p_i)
				p1.pop(p1.index(p_i))
				p_i = p[p_i - 1]
			else:
				end = 0
		cycles.append(cycle)
	for cyc in cycles:
		for k in cyc:
			a[p.index(k)] = len(cyc)
	for x in a:
		print(x, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	s = list(map(int, input().split()))
	f = {}
	ans = {}
	for i in range(1, n + 1):
		f[i] = s[i - 1]
	for i in range(1, n + 1):
		j = i
		c = 1
		while f[j] != i:
			j = f[j]
			c += 1
		ans[i] = c
	print(*list(ans.values()))


for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	for i in range(n):
		res = 1
		ind = i
		while a[ind] - 1 != i:
			ind = a[ind] - 1
			res += 1
		print(res, end=' ')
	print()


def compute(n, arr):
	temp_arr = []
	for i in range(n):
		ans = 1
		cur = arr[i] - 1
		while i != cur:
			ans += 1
			cur = arr[cur] - 1
		temp_arr.append(ans)
	return temp_arr
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	print(*compute(n, arr))


import sys
sys.setrecursionlimit(100000)

def dfs(i, visit, d, a):
	if visit[i] != 0:
		return d
	visit[i] = 1
	visit[i] = dfs(a[i] - 1, visit, d + 1, a)
	return visit[i]
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	visit = [0] * n
	for i in range(n):
		if visit[i] == 0:
			dfs(i, visit, 0, a)
	print(*visit)


for q in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	res = [0] * n
	for i in range(n):
		if res[i] > 0:
			break
		else:
			counter = 1
			j = i
			while p[j] != i + 1:
				j = p[j] - 1
				counter += 1
			res[i] = counter
	print(*res)


q = int(input())
for _ in range(q):
	n = int(input())
	p = list(map(int, input().split()))
	ans = [0] * n
	for i in range(n):
		count = 1
		x = p[i] - 1
		arr = [x]
		if not ans[i]:
			while p[i] != p[x]:
				x = p[x] - 1
				count += 1
				arr.append(x)
			for i in arr:
				ans[i] = count
			ans[i] = count
	print(*ans)


def wczytywanie():
	n = int(input())
	lista_i = []
	lista_i = list(map(int, input().split()))
	return lista_i

def ile_dni():
	lista_i = wczytywanie()
	wielkosc_kolka = [0] * len(lista_i)
	for i in range(len(lista_i)):
		if wielkosc_kolka[i] != 0:
			continue
		else:
			ludzie_na_kolku = [i]
			pozycja = lista_i[i] - 1
			while pozycja != i:
				ludzie_na_kolku.append(pozycja)
				pozycja = lista_i[pozycja] - 1
			ile = len(ludzie_na_kolku)
			for czlowiek in ludzie_na_kolku:
				wielkosc_kolka[czlowiek] = ile
	for i in wielkosc_kolka:
		print(i, end=' ')
n = int(input())
for i in range(n):
	ile_dni()
	print()


def solution(arr, n, i):
	temp = i
	remp = arr[i]
	cnt = 1
	while remp != i:
		(temp, remp) = (remp, arr[remp])
		cnt += 1
	return cnt
q = int(input())
for _ in range(q):
	n = int(input())
	arr = list(map(int, input().strip().split()))
	for i in range(n):
		arr[i] -= 1
	ans = []
	for i in range(n):
		ans.append(solution(arr, n, i))
	print(*ans)


from bisect import *
from collections import *
from itertools import *
import functools
import sys
import math
from decimal import *
from copy import *
from heapq import *
from fractions import *
getcontext().prec = 30
MAX = sys.maxsize
MAXN = 1000010
MOD = 10 ** 9 + 7
spf = [i for i in range(MAXN)]

def sieve():
	for i in range(2, MAXN, 2):
		spf[i] = 2
	for i in range(3, int(MAXN ** 0.5) + 1):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def fib(n, m):
	if n == 0:
		return [0, 1]
	else:
		(a, b) = fib(n // 2)
		c = a % m * (b % m * 2 - a % m) % m
		d = a % m * (a % m) % m + b % m * b % m % m
		if n % 2 == 0:
			return [c, d]
		else:
			return [d, c + d]

def charIN(x=' '):
	return sys.stdin.readline().strip().split(x)

def arrIN(x=' '):
	return list(map(int, sys.stdin.readline().strip().split(x)))

def ncr(n, r):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % MOD
		den = den * (i + 1) % MOD
	return num * pow(den, MOD - 2, MOD) % MOD

def flush():
	return sys.stdout.flush()

def bfs(v):
	q = [v]
	vis[v] = 1
	s = 0
	l = []
	while q:
		x = q.pop(0)
		l.append(x)
		s += 1
		st[x] = s
		for i in d[x]:
			if not vis[i]:
				q.append(i)
				vis[i] = 1
			else:
				t = s + 1 - st[i]
				break
	for i in l:
		ans[i] = t
for _ in range(int(input())):
	n = int(input())
	a = arrIN()
	d = defaultdict(list)
	for i in range(1, n + 1):
		d[i].append(a[i - 1])
	vis = [0] * (n + 1)
	st = [0] * (n + 1)
	ans = [0] * (n + 1)
	for i in range(1, n + 1):
		if not vis[i]:
			bfs(i)
	print(*ans[1:])


q = int(input())
total = []
for qi in range(q):
	n = int(input())
	kids = list(map(int, input().split()))
	answers = [0] * n
	for i in range(n):
		if answers[kids[i] - 1] != 0:
			continue
		tmp = kids[i]
		days = 1
		pairs = [tmp]
		while tmp != i + 1:
			tmp = kids[tmp - 1]
			pairs.append(tmp)
			days += 1
		for p in pairs:
			answers[p - 1] = days
	total.append(answers)
for t in total:
	print(' '.join([str(i) for i in t]))


def solve():
	a = int(input())
	for i in range(0, a):
		input()
		c = list(map(int, input().split(' ')))
		for j in range(1, len(c) + 1):
			count = 1
			k = c[j - 1]
			while k != j:
				count = count + 1
				k = c[k - 1]
			print(count, end=' ')
		print(end='\n')
solve()


for _ in range(int(input())):
	n = int(input())
	res = [1] * n
	arr = list(map(int, input().split()))
	for i in range(n):
		ptr = arr[i]
		count = 0
		if i + 1 == ptr:
			res[i] = 1
		elif i + 1 == arr[ptr - 1]:
			count += 1
			res[i] += count
		else:
			while i + 1 != arr[ptr - 1]:
				ptr = arr[ptr - 1]
				count += 1
			count += 1
			res[i] += count
	for i in res:
		print(i, end=' ')
	print(' ')


t = int(input())
for _ in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	A = [0] + A
	B = [0] * (n + 1)
	for i in range(1, n + 1):
		if B[i] == 0:
			pr = A[i]
			k = 1
			while pr != i:
				pr = A[pr]
				k += 1
			pr = A[i]
			B[pr] = k
			while pr != i:
				pr = A[pr]
				B[pr] = k
	B.pop(0)
	print(*B)


import math
import copy
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	b = [0] * n
	for i in range(n):
		if b[i] != 0:
			continue
		d = []
		d.append(i + 1)
		j = a[i]
		c = 1
		while j != i + 1:
			d.append(j)
			j = a[j - 1]
			c += 1
		for k in d:
			b[k - 1] = c
	for k in b:
		print(k, end=' ')
	print()


import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	ans = []
	for i in range(n):
		(x, c) = (a[i], 0)
		while x != i + 1:
			x = a[x - 1]
			c += 1
		ans.append(c + 1)
	print(*ans)
for _ in range(int(input())):
	solve()


for step in range(int(input())):
	n = int(input())
	P = [int(i) for i in input().split()]
	dict = {}
	sets = []
	for i in range(n):
		if P[i] not in dict:
			test = [P[i]]
			dict[P[i]] = 1
			k = P[P[i] - 1]
			while k != P[i]:
				test.append(k)
				dict[k] = 1
				k = P[k - 1]
			sets.append(test)
	dict2 = {}
	for i in range(len(sets)):
		seti = sets[i]
		for j in seti:
			dict2[j] = len(seti)
	Ans = ''
	for i in P:
		Ans += str(dict2[i]) + ' '
	print(Ans)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr = [0] + arr
	i = 1
	out = []
	while i < n + 1:
		if arr[i] == i:
			out.append(1)
		else:
			j = i
			days = 1
			while arr[j] != i:
				j = arr[j]
				days += 1
			out.append(days)
		i += 1
	print(*out)


Q = int(input())
for q in range(Q):
	N = int(input())
	kids = list(map(int, input().split()))
	new = []
	for n in range(N):
		new.append(0)
	ans = []
	for i in range(len(kids)):
		j = i
		cnt = 0
		while True:
			(new[i], new[kids[i] - 1]) = (new[kids[i] - 1], new[i])
			i = kids[i] - 1
			cnt += 1
			if j == i:
				break
		ans.append(cnt)
	for i in range(len(ans)):
		if i == len(ans) - 1:
			print(ans[i])
		else:
			print(ans[i], end=' ')


amount = int(input())
for i in range(amount):
	n = int(input())
	array = [int(s) - 1 for s in input().split()]
	used = [0] * n
	res = [0] * n
	for j in range(len(array)):
		if used[j] == 0:
			used[j] = 1
			counter = 1
			cycle = [j]
			curr = array[j]
			while curr != j:
				counter += 1
				cycle.append(curr)
				used[curr] = 1
				curr = array[curr]
			for i in range(len(cycle)):
				res[cycle[i]] = counter
	print(' '.join([str(s) for s in res]))


t = int(input())
for _ in range(t):
	_ = input()
	p = list(map(int, input().split()))
	a = set(range(1, len(p) + 1))
	r = [0] * len(p)
	while len(a) != 0:
		ai = a.pop()
		route = {ai}
		cur = ai
		while p[cur - 1] != ai:
			cur = p[cur - 1]
			route.add(cur)
		for el in route:
			r[el - 1] = len(route)
			a.discard(el)
	print(' '.join((str(x) for x in r)))


for _ in range(int(input())):
	n = int(input())
	P = list(map(int, input().split()))
	ans = [0] * n
	for i in range(n):
		if ans[i] == 0:
			now = i
			cnt = 0
			cll = []
			while True:
				now = P[now] - 1
				cnt += 1
				cll.append(now)
				if now == i:
					break
			for u in cll:
				ans[u] = cnt
	print(' '.join(list(map(str, ans))))


def solve():
	n = int(input())
	a = list(map(int, input().split()))
	for i in range(n):
		a[i] -= 1
	ans = dict()
	for i in range(n):
		if i not in ans:
			p = []
			j = i
			p.append(j)
			ca = 0
			while True:
				ca += 1
				j = a[j]
				p.append(j)
				if j == i:
					for x in p:
						ans[x] = ca
					break
	for i in range(n):
		print(ans[i], end=' ')
	print()
for _ in range(int(input())):
	solve()


t = int(input())
for i in range(0, t):
	n = input()
	lista = list(map(int, input().split()))
	glista = lista.copy()
	for j in range(0, len(lista)):
		z = lista[j]
		z = lista[z - 1]
		st = 1
		while z != lista[j]:
			z = lista[z - 1]
			st += 1
		glista[j] = st
	print(*glista)


q = int(input())
for _ in range(q):
	n = int(input())
	l = list(map(int, input().split()))
	l.insert(0, 0)
	c = 1
	for i in range(1, n + 1):
		j = l[i]
		if l[i] == i:
			print(1, end=' ')
			continue
		c = 1
		while True:
			if l[j] == i:
				c += 1
				print(c, end=' ')
				break
			else:
				j = l[j]
				c += 1
	print()


q = int(input().strip())
x = []
n = 0
period = []

def dfs(ori):
	len = 0
	stack = []
	stack.append(ori)
	ls = []
	while stack:
		top = stack.pop()
		ls.append(top)
		len += 1
		if x[top - 1] == ori:
			period[top] = len
			break
		stack.append(x[top - 1])
	for i in ls:
		period[i] = len
for case in range(q):
	n = int(input().strip())
	x = list(map(int, input().strip().split()))
	period.clear()
	period.append(0)
	for i in range(1, n + 1):
		period.append(0)
	for i in range(1, n + 1):
		if period[i] == 0:
			dfs(i)
		print(period[i], end=' ')
	print()


import math
import time
from collections import defaultdict, deque
from sys import stdin, stdout
from bisect import bisect_left, bisect_right

def dfs(root):
	val = []
	q = deque()
	q.append(root)
	visited[i] = True
	while len(q) > 0:
		temp = q.pop()
		val.append(temp)
		if not visited[a[temp - 1]]:
			visited[a[temp - 1]] = True
			q.append(a[temp - 1])
	return val
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	cycles = []
	visited = defaultdict(lambda : False)
	for i in range(1, n + 1):
		if not visited[i]:
			temp = dfs(i)
			cycles.append(temp)
	ans = defaultdict(lambda : 0)
	for i in cycles:
		for j in i:
			ans[j] = len(i)
	for i in range(1, n + 1):
		print(ans[i], end=' ')
	print()


t = int(input())
for i in range(t):
	n = int(input())
	ps = [int(a) for a in input().split()]
	ps.insert(0, 0)
	an = []
	for j in range(1, n + 1):
		ctr = 1
		k = j
		while ps[k] != j:
			ctr += 1
			k = ps[k]
		print(ctr, end=' ')


def Find(Arr, a):
	Flag = -1
	for i in range(len(Arr)):
		if Arr[i] == a:
			Flag = i
			break
	return Flag
q = int(input())
for it in range(q):
	n = int(input())
	A = list(map(int, input().split()))
	Used = [0 for i in range(n)]
	v = 0
	while v != -1:
		Q = [v, A[v] - 1]
		while Q[-1] != Q[0]:
			Q.append(A[Q[-1]] - 1)
		for i in Q:
			Used[i] = len(Q) - 1
		v = Find(Used, 0)
	print(*Used)


q = int(input())
for i in range(q):
	n = int(input())
	l = list(map(int, input().split()))
	l = [0] + l
	ans = [1] * (n + 1)
	d = {}
	for i in range(len(l)):
		if l[i] in d or l[i] == i:
			pass
		else:
			c = 2
			x = l[i]
			vis = [x]
			while 1:
				y = l[x]
				x = y
				vis.append(y)
				key = y
				if key not in d:
					d[key] = 1
				if y == i:
					break
				else:
					c += 1
			for k in range(len(vis)):
				u = vis[k]
				ans[u] = c
	ans = ans[1:]
	print(*ans)


cases = int(input())
for case in range(cases):
	kids_number = int(input())
	kids_list = [int(x) for x in input().split(' ')]
	done_list = [False] * kids_number
	ans_list = [0] * kids_number
	for (i, done) in enumerate(done_list):
		if done:
			continue
		cycle_list = []
		current_kid = i
		while not done_list[current_kid]:
			done_list[current_kid] = True
			cycle_list.append(current_kid)
			current_kid = kids_list[current_kid] - 1
		for cycle in cycle_list:
			ans_list[cycle] = len(cycle_list)
	for ans in ans_list:
		print(ans, end=' ')
	print('')


def main():

	def cmp_to_key(mycmp):

		class K(object):

			def __init__(self, obj, *args):
				self.obj = obj

			def __lt__(self, other):
				return mycmp(self.obj, other.obj) < 0

			def __gt__(self, other):
				return mycmp(self.obj, other.obj) > 0

			def __eq__(self, other):
				return mycmp(self.obj, other.obj) == 0

			def __le__(self, other):
				return mycmp(self.obj, other.obj) <= 0

			def __ge__(self, other):
				return mycmp(self.obj, other.obj) >= 0

			def __ne__(self, other):
				return mycmp(self.obj, other.obj) != 0
		return K
	n = int(input())
	q = list(map(int, input().split()))
	w = [-1] * n
	e = [0] * n
	for i in range(n):
		a = i
		while w[a] == -1:
			w[a] = i
			e[i] += 1
			a = q[a] - 1
	for i in range(n - 1):
		print(e[w[i]], end=' ')
	print(e[w[n - 1]])
for i in range(int(input())):
	main()


from sys import setrecursionlimit

def depth(x, p, a):
	k = 0
	while a[x] != -2:
		a[x] = -2
		k += 1
		x = p[x]
	while a[x] != k:
		a[x] = k
		x = p[x]
	return a[x]

def solve():
	n = int(input())
	p = list(map(lambda x: int(x) - 1, input().split()))
	ans = [-1 for i in range(n)]
	for i in range(n):
		if ans[i] == -1:
			depth(i, p, ans)
	return ans
q = int(input())
for i in range(q):
	print(*solve())


def booksExchange(n, arr):
	arr = [num - 1 for num in arr]
	res = [0 for i in range(n)]
	visited = set()
	for person in range(n):
		if person not in visited:
			cycle = {person}
			count = 1
			temp = person
			while arr[temp] != person:
				cycle.add(temp)
				temp = arr[temp]
				count += 1
			for p in cycle:
				visited.add(p)
				res[p] = count
	return res
res = []
q = int(input())
for i in range(q):
	n = int(input())
	arr = list(map(int, input().split(' ')))
	res.append(booksExchange(n, arr))
for r in res:
	for n in r:
		print(n, end=' ')
	print('')


q = int(input())
for i in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	answ = [-1] * n
	for j in range(n):
		if answ[j] == -1:
			d = 0
			curr = j
			path = []
			while answ[curr] == -1:
				path.append(curr)
				answ[curr] = d + 1
				curr = a[curr] - 1
				d += 1
			for k in range(len(path)):
				answ[path[k]] = d
	print(' '.join([str(x) for x in answ]))


import sys
from collections import deque
readline = sys.stdin.readline
q = int(readline())
for _ in range(q):
	n = int(readline())
	p = [int(x) - 1 for x in readline().split()]
	for i in range(n):
		k = i
		t = 1
		while p[k] != i:
			k = p[k]
			t += 1
		print(t, end=' ')
	print()


import sys
from collections import defaultdict
tests = int(sys.stdin.readline())
for _ in range(tests):
	n = int(sys.stdin.readline())
	arr = list(map(int, sys.stdin.readline().split()))
	dic = defaultdict(set)
	for i in range(n):
		dic[i + 1].add(arr[i])
		prev = 0
		curr = arr[i]
		while prev != len(dic[i + 1]):
			prev = len(dic[i + 1])
			dic[i + 1].add(arr[curr - 1])
			curr = arr[curr - 1]
	for el in dic.items():
		print(len(el[1]), end=' ')
	print()


import sys
sys.setrecursionlimit(10 ** 7)
from collections import deque
import math
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) - 1 for x in input().split()]
	ans = [-1] * n
	for i in range(n):
		if ans[i] == -1:
			cc = [i]
			cur = a[i]
			while cur != i:
				cc.append(cur)
				cur = a[cur]
			for x in cc:
				ans[x] = len(cc)
	for x in ans:
		print(x, end=' ')
	print()


import sys

def get_ints():
	return map(int, sys.stdin.readline().split())
for _ in range(int(input())):
	n = int(input())
	arr = list(get_ints())
	d = {}
	for i in range(n):
		d[i] = arr[i] - 1
	ans = 0
	for i in range(n):
		j = i
		while i != d[j]:
			j = d[j]
			ans += 1
		print(ans + 1, end=' ')
		ans = 0
	print()


from sys import stdin, setrecursionlimit
setrecursionlimit(10 ** 7)

def iin():
	return int(stdin.readline())

def lin():
	return list(map(int, stdin.readline().split()))

class Disjoint_set:

	class node:

		def __init__(self, a):
			self.value = a
			self.p = self
			self.rank = 0

	def __init__(self, a):
		self.data = {i: self.make_set(i) for i in range(1, a + 1)}

	def make_set(self, val):
		return self.node(val)

	def union(self, x, y):
		self.link(self.find_set(self.data[x]), self.find_set(self.data[y]))

	def link(self, val1, val2):
		if val1.rank > val2.rank:
			val2.p = val1
			val1.rank += 1
		else:
			val1.p = val2
			val2.rank += 1

	def find_set(self, val):
		if val.p.value != val.value:
			val.p = self.find_set(val.p)
		return val.p

	def solution(self):
		pr = {}
		parent = {}
		for i in self.data:
			vl = self.find_set(self.data[i]).value
			parent[i] = vl
			if vl in pr:
				pr[vl] += 1
			else:
				pr[vl] = 1
		return (parent, pr)

def main():
	t = iin()
	while t:
		t -= 1
		n = iin()
		p = lin()
		ds = Disjoint_set(n)
		for i in range(n):
			ds.union(i + 1, p[i])
		(ans, pr) = ds.solution()
		sol = [pr[ans[i + 1]] for i in range(n)]
		print(*sol)
main()


test = int(input())
for _ in range(test):
	no = int(input())
	a = list(map(int, input().split()))
	l = set()
	d = [0] * no
	e = [0] * no
	for i in range(no):
		k = a[i]
		if e[i] != 0:
			print(e[i], end=' ')
			continue
		count = 1
		ckt = 0
		while True:
			if k == i + 1 and ckt == 1:
				break
			if k == i + 1 and ckt == 0:
				print(count, end=' ')
				ckt += 1
			if k in l:
				l.remove(k)
				e[k - 1] = count - d[k - 1]
			else:
				d[k - 1] = count
				l.add(k)
			k = a[k - 1]
			count += 1
	print()


import sys
from bisect import bisect
inp = sys.stdin.readline
ans = ''
for _ in range(int(inp())):
	n = int(inp())
	arr = list(map(int, inp().split()))
	dic = dict()
	for (i, elem) in enumerate(arr):
		if not elem in dic:
			m = 1
			j = i
			emp = [i + 1]
			while arr[j] != i + 1:
				emp.append(arr[j])
				j = arr[j] - 1
				m += 1
			for j in emp:
				dic[j] = m
	print(*[dic[j] for j in range(1, n + 1)])


t = int(input())
for tt in range(t):
	n = int(input())
	a = input().split(' ')
	for x in range(n):
		a[x] = int(a[x])
	b = a
	cont = True
	cont2 = True
	while cont2:
		for x in range(n):
			if b[x] > 0:
				j = x
				break
			elif x == n - 1:
				cont = False
		if cont:
			i = j
			c = [i]
			i = b[i] - 1
			while not i == c[0]:
				c.append(i)
				i = b[i] - 1
			lc = len(c)
			for x in c:
				b[x] = -1 * lc
		else:
			cont2 = False
	s = ''
	for x in b:
		s += str(-1 * x)
		s += ' '
	print(s.strip())


t = int(input())
for i in range(t):
	n = int(input())
	d = [int(x) for x in input().split()]
	s = [0] * n
	used = [-1] * n
	for i in range(n):
		if used[i] == -1:
			(u, v) = (i, d[i] - 1)
			while True:
				s[i] += 1
				used[u] = i
				(u, v) = (v, d[v] - 1)
				if u == i:
					break
	res = []
	for j in range(n):
		res.append(s[used[d[j] - 1]])
	print(*res)


q = int(input())
for i in range(0, q):
	n = int(input())
	l = list(map(int, input().split()))
	done = {}
	d = {}
	for j in range(1, n + 1):
		d[j] = l[j - 1]
	for j in range(1, n + 1):
		count = 1
		while d[j] != j:
			d[j] = l[d[j] - 1]
			count += 1
		done[j] = count
	for j in range(1, n + 1):
		print(done[j], end=' ')
	print()


def answer(n, a):
	ans = [1] * n
	for i in range(n):
		k = 1
		c = a[i]
		while c != i:
			k += 1
			c = a[c]
		ans[i] = k
	return ans
q = int(input())
for i in range(q):
	n = int(input())
	a = input().split(' ')
	for i in range(n):
		a[i] = int(a[i]) - 1
	a = answer(n, a)
	for i in range(n):
		a[i] = str(a[i])
	print(' '.join(a))


def solve(p, i):
	pos = p[i]
	ans = 1
	while pos != i:
		ans += 1
		pos = p[pos]
	return ans
q = int(input())
for i in range(q):
	n = int(input())
	arr = list((int(x) - 1 for x in input().split()))
	for i in range(0, n):
		print(solve(arr, i), end=' ')
	print()


q = int(input())
for i in range(q):
	n = int(input())
	x = input()
	y = x.split()
	z = [int(d) for d in y]
	l = []
	for i in range(1, n + 1):
		d = {}
		for j in range(1, n + 1):
			d[j] = z[j - 1]
		count = 1
		while d[i] != i:
			d[i] = d[d[i]]
			count += 1
			i = d[d[i]]
		l.append(count)
	print(*l)


n = int(input())
for i in range(0, n):
	m = int(input())
	lp = list(map(int, input().split()))
	t = []
	visit = [0] * m
	i = 0
	for i in range(0, m):
		if visit[i] == 0:
			t.append([i])
			visit[i] = 1
			x = lp[i] - 1
			while x != i:
				t[-1].append(x)
				visit[x] = 1
				x = lp[x] - 1
	ans = [0] * m
	for i in t:
		ll = len(i)
		for j in i:
			ans[j] = ll
	for i in ans:
		print(i, end=' ')


import sys
I = sys.stdin.readline
for _ in range(int(I())):
	n = int(I())
	p = list(map(int, I().split()))
	d = {}
	for i in range(n):
		d[i] = 1
	for i in d:
		j = i
		while p[j] != i + 1:
			j = p[j] - 1
			d[i] += 1
	print(*list(d.values()))


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	out = [0] * n
	seen = set()
	for x in a:
		if x in seen:
			continue
		current = x
		stack = set()
		while current not in seen and current not in stack:
			stack.add(current)
			current = a[current - 1]
		for x in stack:
			seen.add(x)
			out[x - 1] = len(stack)
	print(*out)


import math
import sys
from collections import defaultdict, Counter
from itertools import groupby
rt = lambda : map(int, input().split())
ri = lambda : int(input())
rl = lambda : list(map(int, input().split()))

def main():
	q = ri()
	for _ in range(q):
		n = ri()
		a = rl()
		used = [False] * n
		res = [0] * n
		for pos in range(n):
			if used[pos]:
				continue
			loop = []
			at = a[pos] - 1
			loop.append(pos)
			while at != pos:
				loop.append(at)
				at = a[at] - 1
			for i in range(len(loop)):
				used[loop[i]] = True
				res[loop[i]] = len(loop)
		print(*[d for d in res])
main()


from sys import stdin

def main():
	input = lambda : stdin.readline()[:-1]
	Q = int(input())
	for _ in [0] * Q:
		N = int(input())
		P = list(map(int, input().split()))
		ans = []
		for (i, p) in enumerate(P, start=1):
			n = 1
			while 1:
				if i == p:
					ans.append(n)
					break
				else:
					p = P[p - 1]
					n += 1
		print(*ans)
main()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [0 for i in range(n)]
	for i in range(n):
		if ans[i] == 0:
			ct = a[i]
			d = 1
			while ct != i + 1:
				d += 1
				ct = a[ct - 1]
			ct = a[i]
			ans[i] = d
			while ct != i + 1:
				ans[ct - 1] = d
				ct = a[ct - 1]
	for i in range(n):
		print(ans[i], end=' ')
	print()


q = int(input())
for _ in range(q):
	d = {}
	n = int(input())
	a = [0] + list(map(int, input().split()))
	b = set()
	for i in range(1, n + 1):
		if i in b:
			continue
		else:
			c = set()
			k = i
			while k not in c:
				c.add(k)
				b.add(k)
				k = a[k]
			l = len(c)
			for i in c:
				d[i] = l
	for i in range(1, n + 1):
		print(d[i], end=' ')
	print()


for i in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	cycle = [0] * (n + 2)
	for j in range(n):
		visited = [False] * (n + 2)
		if visited[j] == False:
			d = 1
			temp = arr[j]
			while temp != j + 1:
				d += 1
				temp = arr[temp - 1]
				visited[temp - 1] = True
		cycle[j] = d
		for k in range(len(cycle)):
			if visited[k] == True:
				cycle[k] = cycle[j]
	print(*cycle[:-2])


def compute(n, arr):
	temp_arr = [0] * n
	used = [False] * n
	for i in range(n):
		if used[i]:
			pass
		else:
			ans = 1
			cur = arr[i] - 1
			cycle = [i]
			while i != cur:
				cycle.append(cur)
				ans += 1
				cur = arr[cur] - 1
			for i in cycle:
				if temp_arr[i] == 0:
					temp_arr[i] = ans
					used[i] = True
	return temp_arr
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	print(*compute(n, arr))


for _ in range(int(input())):
	n = int(input())
	p = list((int(i) - 1 for i in input().split()))
	visited = [0] * n
	ans = [0] * n
	for i in range(n):
		if not visited[i]:
			c = []
			while not visited[i]:
				c.append(i)
				visited[i] = True
				i = p[i]
			for _ in c:
				ans[_] = len(c)
	for _ in range(n):
		print(ans[_], end=' ')
	print()


from collections import defaultdict, deque
from itertools import permutations
from sys import stdin, stdout
from bisect import bisect_left, bisect_right
from copy import deepcopy
int_input = lambda : int(stdin.readline())
string_input = lambda : stdin.readline()
multi_int_input = lambda : map(int, stdin.readline().split())
multi_input = lambda : stdin.readline().split()
list_input = lambda : list(map(int, stdin.readline().split()))
string_list_input = lambda : list(string_input())
MOD = pow(10, 9) + 7
queries = int_input()
for _ in range(queries):
	n = int_input()
	p = list_input()
	result = []
	for i in p:
		count = 1
		book = p[i - 1]
		initial = i
		while book != i:
			book = p[book - 1]
			count += 1
		result.append(count)
	for i in result:
		print(i, end=' ')
	print()


import sys, math
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	w = []
	for i in range(len(a)):
		j = i
		c = 1
		while True:
			q = a[j] - 1
			if q == i:
				qw = c
				break
			else:
				j = q
				c = c + 1
		w.append(c)
	print(*w)


q = int(input())
while q > 0:
	q -= 1
	n = int(input())
	arr = [int(x) - 1 for x in input().split()]
	depth = [-1 for i in range(n)]
	for i in range(n):
		if depth[i] != -1:
			continue
		vis = [i]
		jump = i
		while arr[jump] != i:
			jump = arr[jump]
			vis.append(jump)
		for x in vis:
			depth[x] = len(vis)
	for x in arr:
		print(depth[x], end=' ')
	print()


q = int(input())
for _ in range(q):
	n = int(input())
	p = [int(x) for x in input().split(' ')]
	d = [0 for _ in range(n)]
	for i in range(n):
		seen = []
		if d[i] == 0:
			seen.append(i + 1)
			j = i + 1
			while True:
				j = p[j - 1]
				if i == j - 1:
					break
				seen.append(j)
			c = len(seen)
			for j in seen:
				d[j - 1] = c
	for i in d:
		print(i, end=' ')
	print(' ')


from sys import stdin, stdout
from collections import defaultdict

def dfs(node):
	visited[node] = True
	global size
	size += 1
	global temp
	temp.append(node)
	for i in dic[node]:
		if visited[i] == False:
			dfs(i)
for _i in range(int(stdin.readline())):
	n = int(stdin.readline())
	arr = [int(k) for k in stdin.readline().split()]
	dic = defaultdict(list)
	for i in range(n):
		dic[i + 1].append(arr[i])
	lis = [0] * n
	visited = [False] * (n + 1)
	for i in range(n):
		if visited[i] == False:
			temp = []
			size = 0
			dfs(i)
			for el in temp:
				lis[el - 1] = size
	print(*lis)


import sys

def calc(now, next, val, cnt):
	global temp
	if val == next:
		temp.append(cnt + 1)
		return
	calc(next, arr[next], val, cnt + 1)
tc = int(sys.stdin.readline())
for _ in range(tc):
	n = int(sys.stdin.readline())
	arr = [0] + list(map(int, sys.stdin.readline().split()))
	temp = []
	for i in range(1, n + 1):
		calc(i, arr[i], i, 0)
	print(' '.join(map(str, temp)))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a = [-1] + a
	ans = []
	for i in range(1, n + 1):
		cur = a[i]
		cnt = 0
		while True:
			cnt += 1
			cur = a[cur]
			if cur == a[i]:
				break
		ans.append(cnt)
	print(*ans)


for rpt in range(int(input())):
	kcount = int(input())
	kids = [[int(x) - 1, 0] for x in input().split(' ')]
	for i in kids:
		if i[1] == 0:
			res = 1
			cycle = [i[0]]
			current = kids[i[0]][0]
			while not current == i[0]:
				res += 1
				cycle.append(current)
				current = kids[current][0]
			for i in cycle:
				kids[i][1] = res
	res = ''
	for i in kids:
		res += str(i[1]) + ' '
	print(res)


from sys import stdin, stdout
from heapq import heappush, heappop
import math
import io
import os
import math
import bisect

def isPrime(x):
	for i in range(2, x):
		if i * i > x:
			break
		if x % i == 0:
			return False
	return True

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(int(i))
			n = n / i
	if n > 2:
		l.append(n)
	return list(set(l))

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime

def digits(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def ceil(n, x):
	if n % x == 0:
		return n // x
	return n // x + 1

def mapin():
	return map(int, input().split())
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
q = int(input())
for _ in range(q):
	n = int(input())
	p = [int(x) - 1 for x in input().split()]
	used = [0] * n
	ans = [0] * n
	for j in range(n):
		if used[j] == 0:
			cur = []
			while used[j] == 0:
				cur.append(j)
				used[j] = 1
				j = p[j]
			for i in cur:
				ans[i] = len(cur)
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	p = list(map(lambda x: int(x) - 1, input().split()))
	ans = [-1] * n
	for i in range(n):
		if ans[i] == -1:
			cycle = set()
			u = i
			while u not in cycle:
				cycle.add(u)
				u = p[u]
			for u in cycle:
				ans[u] = len(cycle)
	for elem in ans:
		print(elem, end=' ')
	print()


n = int(input())
for i in range(n):
	num_of_children = int(input())
	list_of_permutations = list(map(int, input().split()))
	list_of_answers = list()
	for el in range(num_of_children):
		counter = 1
		current_position = el
		next_position = list_of_permutations[el] - 1
		while next_position != el:
			current_position = next_position
			next_position = list_of_permutations[current_position] - 1
			counter += 1
		list_of_answers.append(counter)
	print(*list_of_answers)


q = int(input())

def solve():
	n = int(input())
	p = [int(x) for x in input().split()]
	days = [0] * n
	d = 0
	for i in range(n):
		d = 0
		j = p[i] - 1
		d += 1
		while j != i:
			d += 1
			j = p[j] - 1
		days[i] = str(d)
	print(' '.join(days))
for _ in range(q):
	solve()


n = int(input())
for i in range(n):
	result = []
	a = int(input())
	p = list(map(int, input().split()))
	tmpList = p[:]
	for Index in range(a):
		counterDays = 0
		tmp = tmpList[Index] - 1
		while tmp != Index:
			tmp = tmpList[tmp] - 1
			counterDays += 1
		result.append(counterDays + 1)
	print(*result)


q = int(input())
for i in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	ans = []
	for i in range(n):
		f = 1
		curr = a[i]
		while curr - 1 != i:
			curr = a[curr - 1]
			f += 1
		ans.append(f)
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	kids = list(map(int, input().split()))
	res = [None] * n
	for i in range(n):
		if res[i] == None:
			idx = i
			clc = [i]
			num = 1
			while kids[idx] != i + 1:
				idx = kids[idx] - 1
				clc.append(idx)
				num += 1
			for j in clc:
				res[j] = num
	print(*res)


q = int(input())
l = []
for i in range(q):
	n = int(input())
	a = [int(k) for k in input().split(' ')]
	days = [0] * n

	def funcit(x, target, value=0):
		if a[x] == target + 1:
			days[x] = value
		else:
			funcit(a[x] - 1, target, value + 1)
			days[x] = days[a[x] - 1]
	for x in range(n):
		if days[x] == 0:
			xcopy = x
			funcit(x, x, 0)
	l.append(days)
print('\n'.join((' '.join((str(k + 1) for k in p)) for p in l)))


for case in range(int(input())):
	n = int(input())
	p = [0] + list(map(int, input().split()))
	s = [0 for i in range(n + 1)]

	def dfs(x, col, y):
		if p[x] == y:
			s[x] = col + 1
			return s[x]
		s[x] = dfs(p[x], col + 1, y)
		return s[x]
	for i in range(1, n + 1):
		if s[i] == 0:
			s[i] = dfs(i, 0, i)
	print(' '.join(map(str, s[1:])))


q = int(input())
for _ in range(q):
	n = int(input())
	p = list(map(lambda x: int(x) - 1, input().split()))
	a = [0 for i in range(n)]
	for i in range(n):
		if a[i] == 0:
			k = p[i]
			cnt = 1
			cycle = [i]
			while k != i:
				cycle.append(k)
				k = p[k]
				cnt += 1
			for el in cycle:
				a[el] = cnt
	print(*a)


for _ in range(int(input())):
	n_kids = int(input())
	l = list(map(int, input().split()))
	res = [None] * n_kids
	days = 1
	for i in range(n_kids):
		if l[i] == i + 1:
			res[i] = 1
			continue
		else:
			next_kid = l[i]
			while next_kid != i + 1:
				days += 1
				next_kid = l[next_kid - 1]
			(res[i], days) = (days, 1)
	print(*res)


t = int(input())
for _ in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	for i in range(0, n):
		x = p[i]
		c = 1
		while x - 1 != i:
			c += 1
			x = p[x - 1]
		print(c, end=' ')
	print()


def solve_book_passing(book_passing):
	result = []
	for child_index in range(len(book_passing)):
		pass_count = 1
		book_next_pos = book_passing[child_index] - 1
		while book_next_pos != child_index:
			pass_count += 1
			book_next_pos = book_passing[book_next_pos] - 1
		result.append(pass_count)
	return result

def solve_book_passing2(book_passing):
	result = [0 for _ in book_passing]
	visited = [False for _ in book_passing]
	for child_index in range(len(book_passing)):
		if visited[child_index]:
			continue
		current_run = [child_index]
		book_next_pos = book_passing[child_index] - 1
		while book_next_pos != child_index:
			current_run.append(book_next_pos)
			book_next_pos = book_passing[book_next_pos] - 1
		for each in current_run:
			result[each] = len(current_run)
			visited[each] = True
	return result
num_queries = int(input())
results = []
for _ in range(num_queries):
	size_arr = input()
	book_passing = [int(string) for string in input().split(' ')]
	sol = solve_book_passing2(book_passing)
	results.append(' '.join([str(x) for x in sol]))
for r in results:
	print(r)


def func(n, a):
	ans = []
	for i in range(1, n + 1):
		if a[i] == i:
			ans.append(1)
			continue
		else:
			k = a[i]
			count = 1
			while k != i:
				k = a[k]
				count += 1
			ans.append(count)
	return ans
q = int(input())
ans = []
for i in range(0, q):
	n = int(input())
	a = [0 for i in range(n + 2)]
	b = [int(i) for i in input().split()]
	a[1:n + 1] = b
	ans.append(func(n, a))
for i in ans:
	print(*i)


def al(x, l):
	i = l[x]
	t = 1
	while not x == i:
		i = l[i]
		t += 1
	return t

def ab():
	b = int(input())
	c = list(map(int, input().split()))
	for i in range(0, b):
		c[i] = c[i] - 1
	x = []
	for i in range(0, b):
		x.append(al(i, c))
	print(*x)
for i in range(0, int(input())):
	ab()


def Find(x, initial):
	check.append(x)
	if x == initial:
		return 1
	return 1 + Find(arr[x] - 1, initial)
query = int(input())
for _ in range(query):
	n = int(input())
	arr = list(map(int, input().split()))
	result = [0] * n
	for i in range(n):
		if result[i] == 0:
			check = []
			x = Find(arr[i] - 1, i)
			for k in check:
				result[k] = x
	print(' '.join(list(map(str, result))))


from collections import defaultdict as dc
from collections import deque as dq
from bisect import bisect_left, bisect_right, insort_left
import sys
import math
mod = 10 ** 9 + 7

def bs(a, x):
	i = bisect_left(a, x)
	if i != len(a):
		return i
	else:
		return len(a)

def inp():
	p = sys.stdin.readline()
	return p

def line():
	p = list(map(int, inp().split()))
	return p

def bs(a, b):
	l = a
	r = b + 1
	x = b
	ans = 0
	while l < r:
		mid = (l + r) // 2
		if x | mid > ans:
			ans = x | mid
			l = mid + 1
		else:
			r = mid
	return ans

def bsl(a, b):
	l = a
	r = b + 1
	x = b
	ans = 0
	while l < r:
		mid = (l + r) // 2
		if x | mid > ans:
			ans = x | mid
			r = mid - 1
		else:
			l = mid + 1
	return ans
for _ in range(int(input())):
	n = int(inp())
	a = line()
	p = [1] * (n + 1)
	q = dc(int)
	for i in range(n):
		if p[i] == 1 and q[a[i]] == 0:
			j = a[i]
			h = i + 1
			q[a[i]] = h
			c = 0
			while j - 1 < n and h != j:
				q[a[j - 1]] = h
				j = a[j - 1]
				c += 1
			p[i] = p[i] + c
			k = p[i]
		elif p[i] == 1 and q[a[i]] != 0:
			p[i] = p[q[a[i]] - 1]
	print(*p[:-1])


t = int(input())
for _ in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	l = [[] * n for i in range(n)]
	res = [0] * n
	for i in range(n):
		if not l[i]:
			r = []
			while not l[i]:
				r.append(i)
				l[i].append(1)
				i = p[i] - 1
			for j in r:
				res[j] = len(r)
	print(*res)


q = int(input())
for i in range(q):
	t = int(input())
	l = [int(x) for x in input().split()]
	i = 1
	k = []
	for m in l:
		count = 1
		while m != i:
			m = l[m - 1]
			count = count + 1
		k.append(str(count))
		i = i + 1
	print(' '.join(k))


q = int(input())
for _ in range(q):
	n = int(input())
	p = list(map(int, input().split()))
	A = [None] + p
	res = []
	for i in range(1, n + 1):
		temp = A[i]
		cou = 0
		while temp != i:
			temp = A[temp]
			cou += 1
		res.append(cou + 1)
	print(*res)


q = int(input())
for _ in range(q):
	n = int(input())
	p = list(map(int, input().split()))
	ans = [0] * n
	for i in range(n):
		if ans[i] == 0:
			tempArray = []
			start = i
			count = 0
			tempArray.append(i)
			while p[start] != i + 1:
				start = p[start] - 1
				count += 1
				tempArray.append(start)
			for j in tempArray:
				ans[j] = count + 1
	print(*ans)


for _ in range(int(input())):
	j = 0
	n = int(input())
	a = list(map(int, input().split()))
	b = [0] * n
	visit = [-1] * n
	for i in range(n):
		k = i
		c = 0
		while visit[k] == -1:
			c += 1
			visit[k] = j
			k = a[k] - 1
		if c > 0:
			b[j] = c
			j += 1
	for i in visit:
		print(b[i], end=' ')
	print()


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	d = {}
	for i in range(n):
		d[i + 1] = l[i]
	s = ''
	for i in range(n):
		a = 1
		b = i + 1
		while d[b] != i + 1:
			b = d[b]
			a += 1
		s += str(a) + ' '
	print(s)


for i in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	y = []
	a = [0] * n
	for i in range(0, n):
		k = 1
		pos = i
		if a[i] == 0:
			y.append(i + 1)
			while l[pos] != i + 1:
				y.append(l[pos])
				pos = l[pos] - 1
				k = k + 1
			for i in y:
				if a[i - 1] == 0:
					a[i - 1] = k
			y = []
	print(*a)


import sys

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

def mints():
	return map(int, minp().split())

def solve():
	mint()
	a = list(mints())
	b = [True] * len(a)
	r = [0] * len(a)
	for i in range(len(a)):
		if b[i]:
			b[i] = False
			j = a[i] - 1
			c = 1
			while j != i:
				b[j] = False
				j = a[j] - 1
				c += 1
			j = a[i] - 1
			r[i] = c
			while j != i:
				r[j] = c
				j = a[j] - 1
	print(' '.join(map(str, r)))
for i in range(mint()):
	solve()


T = int(input())
for t in range(T):
	n = int(input())
	arr = [0] + list(map(int, input().split()))
	out = []
	hashmap = {}
	for start in range(1, n + 1):
		cur = arr[start]
		cnt = hashmap.get(cur)
		if cnt:
			out.append(cnt)
			continue
		cnt = 1
		numbers = []
		while start != cur:
			numbers.append(cur)
			cur = arr[cur]
			cnt += 1
		out.append(cnt)
		for v in numbers:
			hashmap[v] = cnt
	print(' '.join(map(str, out)))


q = int(input())
for i in range(0, q):
	n = int(input())
	l = list(map(int, input().split()))
	done = {}
	for j in range(1, n + 1):
		if j not in done:
			newly = 0
			x = l[j - 1]
			pos = {x: 1}
			count = 1
			while len(pos) != newly:
				x = l[x - 1]
				count += 1
				if x in pos and x not in done:
					done[x] = count - pos[x]
					newly += 1
				elif x not in pos:
					pos[x] = count
	for j in range(1, n + 1):
		print(done[j], end=' ')
	print()


def badDSU(array):
	for i in range(len(array)):
		array[i] = array[i] - 1
	alls = []
	quotes = []
	for i in range(len(array)):
		if array[i] in quotes:
			continue
		this = []
		if array[i] == i:
			alls.append([i])
			continue
		quotes.append(i)
		this.append(i)
		pointer = array[i]
		while 1:
			if pointer not in this:
				quotes.append(pointer)
				this.append(pointer)
				pointer = array[pointer]
			else:
				alls.append(this)
				break
	ans = [None] * len(array)
	for i in range(len(alls)):
		for j in alls[i]:
			ans[j] = len(alls[i])
	return ans
for _ in range(int(input())):
	n = int(input())
	nums = list(map(int, input().split()))
	days = badDSU(nums)
	print(' '.join(list(map(str, days))))


q = int(input())
for _ in range(q):
	n = int(input())
	p = list(map(int, input().split()))
	ans = [0] * n
	for i in range(n):
		curr = i
		count = 0
		while p[curr] != i + 1:
			curr = p[curr] - 1
			count += 1
		ans[i] = count + 1
	print(*ans)


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, copy, functools
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
mod2 = 998244353
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI():
	return [list(map(int, l.split())) for l in sys.stdin.readlines()]

def LI_():
	return [int(x) - 1 for x in sys.stdin.readline().split()]

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

def I():
	return int(sys.stdin.readline())

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def pe(s):
	return print(str(s), file=sys.stderr)

def JA(a, sep):
	return sep.join(map(str, a))

def JAA(a, s, t):
	return s.join((t.join(map(str, b)) for b in a))

def IF(c, t, f):
	return t if c else f

def YES(c):
	return IF(c, 'YES', 'NO')

def Yes(c):
	return IF(c, 'Yes', 'No')

def main():
	t = I()
	rr = []
	for _ in range(t):
		n = I()
		a = LI_()
		r = [-1] * n
		for i in range(n):
			if r[i] > 0:
				continue
			t = [i]
			c = a[i]
			while c != i:
				t.append(c)
				c = a[c]
			l = len(t)
			for k in t:
				r[k] = l
		rr.append(JA(r, ' '))
	return JA(rr, '\n')
print(main())


q = int(input())
for i in range(q):
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [0] * n
	for j in range(n):
		c = []
		if b[j] != 0:
			continue
		k = a[j] - 1
		count = 1
		c.append(j)
		while k != j:
			c.append(k)
			count += 1
			k = a[k] - 1
		for l in range(count):
			b[c[l]] = count
	print(*b)


import sys
input = sys.stdin.readline
for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	res = [0] * n
	for j in range(n):
		if res[j] == 0:
			tmp = [j]
			con = 1
			ind = a[j] - 1
			while ind != j:
				con += 1
				tmp.append(a[ind] - 1)
				ind = a[ind] - 1
			for _ in tmp:
				res[_] = con
	print(*res)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ll = []
	for i in range(n):
		day = 1
		prev = a[i]
		while prev != i + 1:
			prev = a[prev - 1]
			day += 1
		ll.append(day)
	print(*ll)


def simulate(tab, cur):
	y = tab[cur]
	i = 1
	while y != cur and i < 1000:
		i += 1
		y = tab[y]
	return i

def main():
	q = int(input())
	for x in range(q):
		nb = int(input())
		tab = list(map(int, input().split()))
		for y in range(nb):
			tab[y] -= 1
		for y in range(nb):
			print(simulate(tab, y), end=' ')
		print()
main()


from typing import List

def books_exchange(n: int, p: List[int]):
	a = dict()
	s = set(p)
	while s:
		random_kid = s.pop()
		kid_in_loop = {random_kid}
		while True:
			next_kid = p[random_kid - 1]
			if next_kid in kid_in_loop:
				break
			kid_in_loop.add(next_kid)
			s.remove(next_kid)
			random_kid = next_kid
		count = len(kid_in_loop)
		for kid in kid_in_loop:
			a[kid] = count
	return [a[i] for i in range(1, n + 1)]

def test():
	assert books_exchange(5, [1, 2, 3, 4, 5]) == [1, 1, 1, 1, 1]
	assert books_exchange(3, [2, 3, 1]) == [3, 3, 3]
	assert books_exchange(6, [4, 6, 2, 1, 5, 3]) == [2, 3, 3, 2, 1, 3]
	assert books_exchange(1, [1]) == [1]
	assert books_exchange(4, [3, 4, 1, 2]) == [2, 2, 2, 2]
	assert books_exchange(5, [5, 1, 2, 4, 3]) == [4, 4, 4, 1, 4]
q = int(input())
for _ in range(q):
	n = int(input())
	p = list(map(int, input().split()))
	print(' '.join(map(str, books_exchange(n, p))))


q = int(input())
for test in range(0, q):
	n = int(input())
	st = input().split()
	dic = {}
	check = [-1]
	p = [-1]
	for i in range(0, n):
		check.append(0)
		p.append(int(st[i]))
	lists = []
	for i in range(1, n + 1):
		if check[i] == 0:
			lists.append([i])
			x = p[i]
			l = len(lists)
			dic[i] = l - 1
			while x != i:
				lists[l - 1].append(x)
				check[x] = 1
				dic[x] = l - 1
				x = p[x]
	for i in range(1, n + 1):
		print(len(lists[dic[i]]), end=' ')
	print()


q = int(input())
for i in range(q):

	def acc(x):
		return int(x) - 1
	n = int(input())
	l = list(map(acc, input().split()))
	a = []
	for j in range(n):
		x = j
		c = 1
		while j != l[x]:
			x = l[x]
			c += 1
		a.append(c)
	print(*a)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	i = 0
	b = [1] * n
	while i < n:
		if a[i] == i + 1:
			pass
		else:
			j = i
			x = a[j] - 1
			while x != i:
				x = a[x] - 1
				b[j] += 1
		i += 1
	print(*b)


import sys
from collections import deque
tcs = int(input())
for _ in range(tcs):
	n = int(input())
	num = [0] + list(map(int, sys.stdin.readline().rstrip().split()))
	visited = [0] * (n + 1)
	for i in range(1, n + 1):
		if visited[i] == 0:
			que = deque()
			que.append(i)
			vis = []
			while len(que) != 0:
				pick = que.pop()
				vis.append(pick)
				visited[pick] = 1
				if visited[num[pick]] == 0:
					que.appendleft(num[pick])
			cnt = len(vis)
			while len(vis) != 0:
				visited[vis.pop()] = cnt
	for i in range(1, n + 1):
		print(visited[i], end=' ')
	print()


q = int(input())
for i in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	for j in range(len(a)):
		x = a[j] - 1
		k = 1
		while x != j:
			x = a[x] - 1
			k += 1
		print(k, end=' ')
	print()


q = int(input())
for _ in range(q):
	n = int(input())
	p = [int(x) - 1 for x in input().split()]
	visited = [False] * n
	values = [0] * n
	for i in range(n):
		count = 1
		x = p[i]
		temp_loc = [x]
		if not visited[i]:
			while x != i:
				x = p[x]
				temp_loc.append(x)
				visited[x] = True
				count += 1
			for y in temp_loc:
				values[y] = count
	for v in values:
		print(v, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	p = [0] + list(map(int, input().split()))
	array = []
	for i in range(1, n + 1):
		c = 1
		k = p[i]
		while k != i:
			k = p[k]
			c += 1
		array.append(c)
	print(*array)


mod = 10 ** 9 + 7
import sys
from sys import stdin, stdout
for _ in range(int(input())):
	n = int(input())
	a = []
	a.append(0)
	a += [int(n) for n in input().split()]
	b = []
	x = {}
	for i in range(1, n + 1):
		j = i
		y = []
		if i not in x:
			y.append(j)
			while i != a[j]:
				j = a[j]
				y.append(j)
			l = len(y)
			for j in y:
				x[j] = l
		b.append(x[i])
	print(*b)


import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
for tc in range(int(input())):
	(n,) = I()
	l = [int(i) - 1 for i in input().split()]
	p = [0] * n
	an = []
	for i in range(n):
		po = l[i]
		ans = 1
		while po != i:
			ans += 1
			po = l[po]
		an.append(ans)
	print(*an)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	l = set()
	d = [0] * n
	e = [0] * n
	for i in range(n):
		k = a[i]
		if e[i] != 0:
			print(e[i], end=' ')
			continue
		cnt = 1
		ckt = 0
		while True:
			if k == i + 1 and ckt == 0:
				print(cnt, end=' ')
				ckt += 1
			elif k == i + 1 and ckt == 1:
				break
			if k in l:
				l.remove(k)
				e[k - 1] = cnt - d[k - 1]
			else:
				d[k - 1] = cnt
				l.add(k)
			k = a[k - 1]
			cnt += 1
	print()


t = int(input())
for _ in range(t):
	n = int(input())
	a = [0] + list(map(int, input().split()))
	res = [0] * (n + 1)
	mark = [0] * (n + 1)
	for i in range(1, n + 1):
		temp = a[i]
		if mark[temp] == 0:
			mark[temp] = i
			step = 1
			while temp != i:
				temp = a[temp]
				mark[temp] = i
				step += 1
			res[i] = step
	for i in range(1, n + 1):
		print(res[mark[i]], end=' ')
	print()


from sys import stdin, stdout
q = int(stdin.readline())
for i in range(q):
	n = int(stdin.readline())
	ans = [0] * n
	arr = [int(x) for x in stdin.readline().split()]
	visited = [0] * n
	length = [0] * n
	for j in range(n):
		temp_array = []
		if visited[j] == 0:
			visited[j] = 1
			temp = arr[j]
			count = 1
			temp_array.append(j)
			while visited[temp - 1] == 0:
				visited[temp - 1] = 1
				count += 1
				temp_array.append(temp - 1)
				temp = arr[temp - 1]
			for k in range(len(temp_array)):
				ans[temp_array[k]] = count
	for l in range(n):
		stdout.write(str(ans[l]) + ' ')
	stdout.write('\n')


for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	for i in range(1, n + 1):
		days = 1
		current = p[i - 1]
		while current != i:
			days += 1
			current = p[current - 1]
		print(days, end=' ')
	print('')


def minSwaps(arr):
	n = len(arr)
	vis = {k: False for k in range(n)}
	par = {k: 0 for k in range(n)}
	for i in range(n):
		if vis[arr[i]]:
			continue
		cycle_size = 0
		j = i
		curr = []
		while not vis[arr[j]]:
			curr.append(arr[j])
			vis[arr[j]] = True
			j = arr[j]
			cycle_size += 1
		if cycle_size > 0:
			for f in curr:
				par[f] = cycle_size
	return par
q = int(input())
for _ in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	for i in range(len(a)):
		a[i] -= 1
	d = minSwaps(a)
	for i in a:
		print(d[i], end=' ')
	print()


def f():
	q = int(input())
	for i in range(q):
		n = int(input())
		p = [0] + [int(x) for x in input().split()]
		print(getDays(n, p))

def getDays(numKids, p):
	if numKids == 1:
		return 1
	days = [1] + [0] * numKids
	for x in range(len(days)):
		if days[x] == 0:
			k = x
			nextk = p[k]
			loop = [k]
			while nextk != k:
				loop.append(nextk)
				nextk = p[nextk]
			for i in loop:
				days[i] = len(loop)
	days_string = ' '.join(map(str, days[1:]))
	return days_string
f()


queries = int(input())
for x in range(queries):
	kids = int(input())
	p = input()
	p = p.split()
	for i in p:
		pos = int(p[int(i) - 1])
		ans = 1
		while int(pos) != int(i):
			ans += 1
			pos = p[int(pos) - 1]
		print(ans, end=' ')
	print('\n')


q = int(input())
for iwe in range(q):
	n = int(input())
	l = list(map(int, input().split()))
	l = [l[i] - 1 for i in range(n)]
	odp = [0] * n
	odw = [0] * n
	for i in range(n):
		if odw[i] != 0:
			continue
		cur = i
		dl = 1
		ziomy = []
		while True:
			odw[cur] = 1
			ziomy.append(cur)
			cur = l[cur]
			if cur == i:
				break
			dl += 1
		for v in ziomy:
			odp[v] = dl
	print(*odp)


q = int(input())
for i in range(q):
	w = int(input())
	e = list(map(int, input().split()))
	r = [-1] * w
	color = 0
	col = []
	for j in range(w):
		if r[j] == -1:
			k = 0
			while r[j] != color:
				r[j] = color
				j = e[j] - 1
				k += 1
			col.append(k)
			color += 1
	for j in r:
		print(col[j], end=' ')
	print()


for i in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l1 = []
	d = {}
	count = 0
	for j in range(n):
		d[j] = -1
	for j in range(n):
		if d[j] == -1:
			l1.append([])
			l1[count].append(j + 1)
			d[j] = count
			k = j
			while True:
				if l[k] == j + 1:
					break
				l1[count].append(l[k])
				k = l[k] - 1
				d[k] = count
			count += 1
	for j in range(n):
		print(len(l1[d[j]]), end=' ')
	print()


import sys
q = int(input())
for x in range(q):
	n = int(input())
	ans = [-1] * n
	p = [int(i) for i in input().split()]
	for i in range(n):
		ch = p[i]
		count = 0
		cy = [i + 1]
		if ans[i] == -1:
			while ch != i + 1:
				cy.append(ch)
				ch = p[ch - 1]
				count += 1
			for w in cy:
				ans[w - 1] = count + 1
	for h in range(n):
		print(ans[h], end=' ')
	print()


class UnionFind:

	def __init__(self, size):
		self.data = [-1] * size

	def find(self, x):
		if self.data[x] < 0:
			return x
		else:
			self.data[x] = self.find(self.data[x])
			return self.data[x]

	def union(self, x, y):
		(x, y) = (self.find(x), self.find(y))
		if x != y:
			if self.data[y] < self.data[x]:
				(x, y) = (y, x)
			self.data[x] += self.data[y]
			self.data[y] = x
		return x != y

	def same(self, x, y):
		return self.find(x) == self.find(y)

	def size(self, x):
		return -self.data[self.find(x)]

def main():
	Q = int(input())
	for _ in range(Q):
		N = int(input())
		P = [int(i) - 1 for i in input().split()]
		uf = UnionFind(N)
		for (i, p) in enumerate(P):
			uf.union(i, p)
		print(*(uf.size(i) for i in range(N)))
main()


def main():

	def find(x):
		if par[x] == x:
			return x
		else:
			par[x] = find(par[x])
			size[x] = size[par[x]]
			return par[x]

	def same(x, y):
		return find(x) == find(y)

	def union(x, y):
		x = find(x)
		y = find(y)
		if x == y:
			return
		if size[x] < size[y]:
			(x, y) = (y, x)
		size[x] += size[y]
		par[y] = x

	def get_size(x):
		return size[find(x)]
	Q = int(input())
	for _ in range(Q):
		N = int(input())
		P = [int(i) - 1 for i in input().split()]
		par = [i for i in range(N)]
		size = [1 for i in range(N)]
		for (i, p) in enumerate(P):
			union(i, p)
		for i in range(N):
			print(get_size(i), end=' ' if i != N - 1 else '\n')
main()


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	d = {}
	for j in range(n):
		d[j + 1] = a[j]
	visited = [0] * n
	ans = []
	ansd = {}
	for j in range(n):
		s = [a[j]]
		se = set()
		while s:
			node = s.pop(0)
			if visited[node - 1] == 0:
				visited[node - 1] = 1
				se.add(node)
				s.append(d[node])
		if len(se) != 0:
			ans.append(se)
	for j in range(len(ans)):
		p = len(ans[j])
		for k in ans[j]:
			ansd[k] = p
	for j in range(n):
		print(ansd[a[j]], end=' ')
	print()


q = int(input())
for _ in range(q):
	n = int(input())
	p = [0] + [int(x) for x in input().split()]
	ans = [0] * (n + 1)
	for i in range(1, n + 1):
		kid = p[i]
		if ans[kid] != 0:
			continue
		day = 1
		lst = [kid]
		while kid != i:
			kid = p[kid]
			day += 1
			lst.append(kid)
		for l in lst:
			ans[l] = day
	print(*ans[1:])


import sys
input = sys.stdin.readline
for j in range(int(input())):
	y = int(input())
	arr = list(map(int, input().split()))
	flw = [0] * y
	for i in range(y):
		if flw[i] == 0:
			ind = i
			count = 1
			res = [i]
			while arr[ind] != i + 1:
				count += 1
				ind = arr[ind] - 1
				res.append(ind)
			for _ in res:
				flw[_] = count
	print(*flw, end=' ')
	print()


def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))
q = int(input())
for _ in range(q):
	n = int(input())
	p = [-1] + [int(x) for x in input().split()]
	explored = [False for __ in range(n + 1)]
	ans = [-1 for _ in range(n + 1)]
	for i in range(1, n + 1):
		if explored[i] == False:
			gp = list()
			j = i
			while explored[j] == False:
				explored[j] = True
				j = p[j]
				gp.append(j)
			for x in gp:
				ans[x] = len(gp)
	oneLineArrayPrint(ans[1:])


def dfs(node, cclist, curr):
	stack = [node]
	while stack:
		node = stack.pop()
		cclist[node] = curr
		for nbr in g[node]:
			if cclist[nbr] == 0:
				stack.append(nbr)
from sys import stdin, stdout, setrecursionlimit
from collections import defaultdict, Counter
q = int(input())
for _ in range(q):
	n = int(input())
	nums = list(map(int, stdin.readline().strip().split()))
	g = [[] for _ in range(len(nums) + 1)]
	for (i, pi) in enumerate(nums):
		g[i + 1].append(pi)
	cclist = [0] * (n + 1)
	curr = 1
	for i in nums:
		if cclist[i] == 0:
			dfs(i, cclist, curr)
			curr += 1
	freq = Counter(cclist[1:])
	print(*[freq[cclist[i]] for i in nums])


q = int(input())
for i in range(q):
	n = int(input())
	a = input().split()
	for p in range(len(a)):
		a[p] = int(a[p]) - 1
	for j in range(n):
		cnt = 1
		tmp = j
		while 1:
			if a[tmp] == j:
				print(cnt, end=' ')
				break
			tmp = a[tmp]
			cnt += 1
	print('')


for _ in range(int(input())):
	n = int(input())
	p = [-1] + list(map(int, input().split()))
	cycle = [-1] * (n + 1)
	for i in range(1, n + 1):
		if cycle[i] == -1:
			if p[i] == i:
				cycle[i] = 1
				continue
			cur = p[i]
			cnt = 1
			while cur != i:
				cnt += 1
				cur = p[cur]
			cycle[i] = cnt
			cur = p[i]
			while cur != i:
				cycle[cur] = cnt
				cur = p[cur]
	for i in range(1, n + 1):
		print(cycle[i], end=' ')
	print()


testCases = int(input())
for i in range(testCases):
	number = int(input())
	p = [int(i) for i in input().split()]
	vertices = [None] * number
	for j in range(number):
		if vertices[j] is None:
			k = j
			vertices[j] = [j]
			while j != p[k] - 1:
				vertices[j].append(p[k] - 1)
				vertices[p[k] - 1] = vertices[j]
				k = p[k] - 1
	print(*[len(v) for v in vertices])


from collections import Counter
from collections import defaultdict
import math
t = int(input())
for _ in range(0, t):
	n = int(input())
	a = list(map(int, input().split()))
	for i in range(0, n):
		c = i + 1
		d = a[i]
		ans = 1
		while d != c:
			d = a[d - 1]
			ans = ans + 1
		print(ans, end=' ')
	print()


q = int(input())
res = []
for i in range(q):
	n = int(input())
	p = list(map(int, input().split()))
	res.append([])
	for k in range(n):
		start = k
		cont = p[k] - 1
		c = 1
		if start == cont:
			res[i].append(c)
			continue
		while start != cont:
			cont = p[cont] - 1
			c += 1
		res[i].append(c)
for i in range(q):
	print(*res[i])


for q in range(int(input())):
	n = int(input())
	l = list(map(int, input().split(' ')))
	i = 0
	while i < len(l):
		if l[i] > 0:
			loop = [i + 1]
			v = l[i]
			while v != loop[0]:
				loop.append(v)
				v = l[v - 1]
			length = len(loop)
			for x in loop:
				l[x - 1] = -length
		i += 1
	for i in l:
		print(-i, end=' ')
	print()


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	lf = []
	for i in range(n):
		co = 1
		target = i + 1
		holder = l[i]
		while holder != target:
			co += 1
			holder = l[holder - 1]
		lf.append(co)
	print(*lf, sep=' ')


def dfs(a):
	vis_set = set()
	ret = [0] * len(a)
	for ele in a:
		if ele not in vis_set:
			res = []
			stack = [ele]
			while stack:
				vert = stack.pop()
				vis_set.add(vert)
				res.append(vert)
				next = a[vert - 1]
				if next not in vis_set:
					stack.append(next)
			for ele in res:
				ret[ele - 1] = len(res)
	return ret
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ans = dfs(a)
	print(*ans)


n = int(input())
ss = []
for i in range(n):
	input()
	ss += [list(map(int, input().split(' ')))]
for i in range(n):
	s = ss[i]
	S = [1 for j in range(len(s))]
	for j in range(1, len(s) + 1):
		if S[j - 1] != 1:
			continue
		v = s[j - 1]
		vs = []
		while v != j:
			v = s[v - 1]
			vs += [v]
			S[j - 1] += 1
		for k in range(len(vs)):
			S[vs[k] - 1] = S[j - 1]
	print(' '.join(list(map(str, S))))


Q = int(input())
for _ in range(Q):
	N = int(input())
	P = [int(i) - 1 for i in input().split()]
	A = list(range(N))
	B = [0] * N
	ans = [0] * N
	for cnt in range(1, N + 1):
		for (a, p) in zip(A, P):
			B[p] = a
			if p == a and ans[p] == 0:
				ans[p] = cnt
		A = B[:]
	print(*ans)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = [-1] * n
	for i in range(n):
		if b[i] == -1:
			c = 1
			d = a[i] - 1
			while d != i:
				c += 1
				d = a[d] - 1
			d = a[i] - 1
			b[i] = c
			while d != i:
				b[d] = c
				d = a[d] - 1
	print(*b)


def returns_in(n, p_kids):
	answer = [0] * n
	for i in range(n):
		his_book = i + 1
		current_book = -1
		next_book = p_kids[i]
		k = 0
		while current_book != his_book:
			current_book = next_book
			next_book = p_kids[current_book - 1]
			k += 1
		answer[i] = k
	return ' '.join([str(i) for i in answer])
q = int(input())
for _ in range(q):
	n = int(input())
	p_kids = list(map(int, input().split()))
	print(returns_in(n, p_kids))


q = int(input())
ans = []
for i in range(q):
	n = int(input())
	p = list(map(int, input().split()))
	ans_z = []
	for j in range(n):
		count = 1
		k = j
		while j != p[k] - 1:
			count += 1
			k = p[k] - 1
		else:
			ans_z.append(count)
	ans.append(ans_z)
for i in ans:
	print(*i)


for _ in range(int(input())):
	n = int(input())
	p = list(map(lambda x: int(x) - 1, input().split()))
	used = [False] * n
	ans = [0] * n
	for i in range(n):
		if used[i]:
			continue
		elem = i
		cnt = 0
		cycle = []
		while not used[elem]:
			used[elem] = True
			cnt += 1
			cycle.append(elem)
			elem = p[elem]
		for j in cycle:
			ans[j] = cnt
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	a = []
	for i in range(n):
		a.append(i + 1)
	ans = [0] * n
	vis = [False] * n
	temp = [0] * n
	x = 0
	v = 0
	while x < n:
		for i in range(n):
			temp[arr[i] - 1] = a[i]
		v += 1
		a = temp[:]
		for i in range(n):
			if a[i] - 1 == i:
				if not vis[i]:
					ans[i] = v
					vis[i] = True
					x += 1
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	d = {}
	c = {}
	for i in range(n):
		a[i] -= 1
		d[i] = a[i]
		c[i] = 1
	for i in range(n):
		for j in range(n):
			k = min(a[j], a[d[j]])
			if k != a[j]:
				c[k] += c[a[j]]
				c[a[j]] = 0
			a[j] = k
	print(*[c[x] for x in a])


import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	n = int(input())
	a = [int(x) - 1 for x in input().split()]
	vis = [False] * n
	ans = [-1] * n
	for i in range(n):
		if not vis[i]:
			j = i
			b = []
			while not vis[j]:
				vis[j] = True
				b.append(j)
				j = a[j]
			for x in b:
				ans[x] = len(b)
	print(*ans)


q = int(input())
r = []

def f(l, m, i, s, j):
	if i == j:
		return s
	m[j] = f(l, m, i, s + 1, l[j] - 1)
	return m[j]
for p in ' ' * q:
	n = int(input())
	(*l,) = map(int, input().split())
	m = [0] * n
	for i in range(n):
		if m[i] == 0:
			m[i] = f(l, m, i, 1, l[i] - 1)
	r += [m]
for i in r:
	print(*i)


t = int(input())
for _ in range(t):
	n = int(input())
	a = [0] + list(map(int, input().split()))
	v = [0] * (n + 1)
	cmp = []
	for i in range(1, 1 + n):
		if not v[i]:
			v[i] = 1
			t = [a[i]]
			cr = a[a[i]]
			while cr != a[i]:
				t.append(cr)
				v[cr] = 1
				cr = a[cr]
			cmp.append(t)
	bckt = [0] * (n + 1)
	for i in cmp:
		for j in i:
			bckt[j] = len(i)
	print(*bckt[1:])


q = int(input())

def answer(ls):
	n = len(ls)
	answers = [0] * n
	for i in range(1, n + 1):
		start = ls[i - 1]
		k = start
		counter = 0
		while True:
			counter += 1
			k = ls[k - 1]
			if k == start:
				answers[i - 1] = counter
				break
	return answers
for _ in range(q):
	n = int(input())
	ls = list(map(int, input().split()))
	answers = answer(ls)
	print(' '.join(map(str, answers)))


def find(k):
	global done
	if done[k] == 1:
		return
	this = k
	while array[k] != k:
		done[k] = 1
		temp = array[k]
		array[k] = this
		k = temp
for _ in range(int(input())):
	n = int(input())
	array = list(map(int, input().split()))
	array = [i - 1 for i in array]
	done = [0] * len(array)
	for i in range(n):
		find(i)
	mydick = {}
	for i in array:
		mydick[i] = mydick.get(i, 0) + 1
	ans = []
	for i in array:
		ans.append(mydick[i])
	print(*ans)


from collections import defaultdict

class Graph:

	def __init__(self, N):
		self.n = N
		self.graph = defaultdict(list)

	def add(self, arr):
		visited = [0] * (self.n + 1)
		ans = [0] * (self.n + 1)
		for i in range(1, self.n + 1):
			if visited[i] == 0:
				curr = i
				nextEle = arr[i - 1]
				visited[curr] = 1
				status = []
				status.append(curr)
				count = 1
				while nextEle != curr:
					visited[nextEle] = 1
					status.append(nextEle)
					nextEle = arr[nextEle - 1]
					count += 1
				for i in status:
					ans[i] = count
		return ans
for test in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	g = Graph(n)
	for i in g.add(arr)[1:]:
		print(i, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	p = [int(i) - 1 for i in input().split()]
	for kid in range(n):
		d = 1
		i = kid
		while kid != p[i]:
			i = p[i]
			d += 1
		print(d, end=' ')
	print()


def bar(N, Ps):
	visited = [False] * N
	rooty = [n for n in range(N)]
	cycles = {}
	for parent in range(N):
		level = 1
		temp = parent
		if not visited[parent]:
			while True:
				visited[temp] = True
				rooty[temp] = parent
				temp = Ps[temp] - 1
				if temp == parent:
					break
				level += 1
		cycles[parent] = level
	return ' '.join([str(cycles[rooty[node]]) for node in range(N)])

def zoo(node, pnode, Ps, parent, cycles, level=1):
	pn = parent.get(node, None)
	if pn is not None:
		return cycles[pn]
	parent[node] = pnode
	next = Ps[node] - 1
	if next == pnode:
		return level
	else:
		return zoo(next, pnode, Ps, parent, cycles, level + 1)

def foo(N, Ps):
	parent = {}
	cycles = {}
	for node in range(N):
		cycle = zoo(node, node, Ps, parent, cycles, 1)
		cycles[node] = cycle
	return ' '.join([str(cycles[node]) for node in range(N)])
T = int(input())
for i in range(T):
	N = int(input())
	Ps = list(map(int, input().split()))
	print(bar(N, Ps))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	vis = [0 for _ in range(n)]
	for i in range(n):
		if vis[i]:
			continue
		day = 1
		prev = a[i] - 1
		temp = [i]
		while prev != i:
			day += 1
			temp.append(prev)
			prev = a[prev] - 1
		for j in range(len(temp)):
			vis[temp[j]] = day
	print(*vis)


for _ in range(int(input())):
	n = int(input())
	a = [0] + list(map(int, input().split()))
	vis = [0] * (n + 1)
	vis1 = [0] * (n + 1)
	ans1 = [1] * (n + 1)
	for i in range(1, n + 1):
		if vis[i] == 0:
			ans = 0
			ind = i
			while vis[ind] != 1:
				ans += 1
				vis[ind] = 1
				ind = a[ind]
			ind = i
			while vis1[ind] != 1:
				ans1[ind] = ans
				vis1[ind] = 1
				ind = a[ind]
	print(*ans1[1:])


t = int(input())
for i in range(0, t):
	n = int(input())
	a = list(map(int, input().split()))
	flag = 0
	k = 1
	ans = []
	while flag == 0:
		count = 1
		temp = k - 1
		flag2 = 0
		while flag2 == 0:
			if a[temp] == k:
				flag2 = 1
			else:
				temp = a[temp] - 1
				count = count + 1
		ans.append(count)
		if k == n:
			flag = 1
		k = k + 1
	for j in range(0, n):
		print(ans[j], end=' ')
		if j == n - 1:
			print()


q = int(input())
for _ in range(q):
	n = int(input())
	arr = list(map(lambda x: int(x) - 1, input().split()))
	for (idx, child) in enumerate(arr):
		count = arr[idx]
		ans = 1
		while count != idx:
			count = arr[count]
			ans += 1
		print(ans, end=' ')
	print()


input = __import__('sys').stdin.readline
for _ in range(int(input())):
	n = int(input())
	s = list(map(lambda x: int(x) - 1, input().split()))
	cnt = 0
	kids = {}
	ans = [0] * n
	for i in range(n):
		kids[i] = s[i]
	while kids:
		f = min(kids)
		cc = 0
		t = []
		while 1:
			t.append(f)
			if f in kids:
				f = kids.pop(f)
			else:
				break
			cc += 1
		for i in t:
			ans[i] = cc
		cnt += 1
	print(*ans)


quant = int(input())
respostaFinal = []
for u in range(quant):
	kid = int(input())
	resposta = []
	lista = list(map(int, input().split()))
	for k in lista:
		valorF = k
		cont = 1
		for i in range(len(lista)):
			if lista[valorF - 1] == k:
				break
			else:
				cont += 1
				valorF = lista[valorF - 1]
		resposta.append(cont)
	respostaFinal.append(resposta)
for i in respostaFinal:
	for k in i:
		print(str(k) + ' ', end='')
	print()


import sys, math

def input():
	return sys.stdin.readline()[:-1]

def main():
	q = int(input())
	for _ in range(q):
		n = int(input())
		p = list(map(int, input().split()))
		ans = [0 for k in range(n)]
		for k in range(n):
			if ans[k] > 0:
				pass
			else:
				temp = p[k]
				t = 1
				l = [p[k]]
				while temp != k + 1:
					l.append(p[temp - 1])
					temp = p[temp - 1]
					t += 1
				for e in l:
					ans[e - 1] = t
		print(*ans, sep=' ')
main()


for q in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	b = []
	for i in range(n):
		ans = a[i]
		c = 1
		while ans != i + 1:
			ans = a[ans - 1]
			c += 1
		b.append(c)
	print(*b)


q = int(input())
for qq in range(q):
	n = int(input())
	num = input()
	p = [int(x) for x in num.split()]
	vis = [0] * n
	ans = [0] * n
	for i in range(len(p)):
		if ans[i] != 0:
			continue
		x = p[i]
		ans[i] = 1
		y = []
		while x != i + 1:
			ans[i] += 1
			y.append(x)
			x = p[x - 1]
		for j in y:
			ans[j - 1] = ans[i]
	print(*ans)


t = int(input())
for you in range(t):
	n = int(input())
	l = input().split()
	li = [int(i) - 1 for i in l]
	hashi = dict()
	for i in range(n):
		if i not in hashi:
			l = [i]
			curr = li[i]
			count = 0
			while curr != i:
				l.append(curr)
				curr = li[curr]
				count += 1
			for z in l:
				hashi[z] = count
	for i in range(n):
		print(hashi[i] + 1, end=' ')
	print()


def solve():
	n = int(input())
	p = [0] + list(map(int, input().split()))
	for i in range(1, n + 1):
		pos = p[i]
		ans = 1
		while pos != i:
			ans += 1
			pos = p[pos]
		print(ans, end=' ')
	print()
for _ in range(int(input())):
	solve()


for i in range(int(input())):
	a = int(input())
	b = list(map(int, input().split()))
	b.insert(0, 0)
	for i in range(1, a + 1):
		j = b[i]
		c = 0
		while i != j:
			c += 1
			j = b[j]
		print(c + 1, end=' ')
	print()


for i in range(int(input())):
	n = int(input())
	l1 = list(map(int, input().split()))
	t = 0
	for j in range(1, n + 1):
		x = j - 1
		count = 0
		for kk in range(n):
			t = l1[x]
			x = t - 1
			count += 1
			if t == j:
				break
		print(count, end=' ')
	print('')


for _ in range(int(input())):
	n = int(input())
	a = [int(i) - 1 for i in input().split()]
	c = []
	for i in range(n):
		j = i
		s = 1
		while a[j] != i:
			s += 1
			j = a[j]
		c.append(s)
	print(*c)


global c

def dfs(x, i, count):
	if x == i:
		return count
	c.append(x)
	return dfs(a[x], i, count + 1)
q = int(input())
for _ in range(q):
	n = int(input())
	vis = [False for i in range(n + 1)]
	q = list(map(int, input().split()))
	a = [0]
	for i in q:
		a.append(i)
	ans = [-1 for i in range(n + 1)]
	for i in range(1, n + 1):
		if vis[i] == False:
			c = [i]
			k = dfs(a[i], i, 1)
			for x in c:
				ans[x] = k
	for i in range(1, n):
		print(ans[i], end=' ')
	print(ans[n])


from collections import *
from math import *

def I():
	return map(int, input().strip().split())
for Q in range(int(input())):
	n = int(input())
	arr = [0] + list(I())
	for i in range(1, n + 1):
		ans = 1
		own = arr[i]
		while own != i:
			own = arr[own]
			ans += 1
		print(ans, end=' ')
	print()


import sys
t = int(sys.stdin.readline())
for _ in range(t):
	n = int(sys.stdin.readline())
	arr = [0] + list(map(int, sys.stdin.readline().split()))
	result = []
	for i in range(1, n + 1):
		day = 1
		idx = arr[i]
		if idx == i:
			result.append(day)
		else:
			while idx != i:
				day += 1
				idx = arr[idx]
			result.append(day)
	result = ' '.join(list(map(str, result)))
	print(result)


for i in range(int(input())):
	n = int(input())
	ans = [0] * n
	arr = list(map(int, input().split()))
	for i in range(n):
		if arr[i] != i + 1:
			if arr[arr[i] - 1] == i + 1:
				ans[i] = 2
				ans[arr[i] - 1] = 2
			else:
				c = 0
				ic = arr[i] - 1
				l = []
				l.append(ic)
				while ic != i:
					ic = arr[ic] - 1
					l.append(ic)
				p = len(l)
				for i in l:
					ans[i] = p
		else:
			ans[i] = 1
	print(*ans)


q = int(input())
for i in range(q):
	n = int(input())
	a = [int(i) for i in input().split()]
	c = [0 for i in range(n)]
	for j in range(n):
		b = []
		if c[j] == 0:
			b.append(j)
			p = a[j] - 1
			while p != b[0]:
				b.append(p)
				p = a[p] - 1
			for k in b:
				c[k] = len(b)
	print(' '.join([str(k) for k in c]))


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	ans = [0] * n
	for i in range(n):
		if ans[i] == 0:
			seen = []
			temp = arr[i] - 1
			curr_cnt = 1
			while temp != i:
				seen.append(temp)
				temp = arr[temp] - 1
				curr_cnt += 1
			ans[i] = curr_cnt
			for j in seen:
				ans[j] = curr_cnt
	print(*ans)


q = int(input().strip())

def to_root(a, p):
	while a != p[a]:
		a = p[a]
	return a

def equal(a, b, p):
	while a != p[a]:
		a = p[a]
	while b != p[b]:
		b = p[b]
	return (a, b)
for _ in range(q):
	n = int(input().strip())
	children = [int(i) for i in input().strip().split()]
	parent_tree = dict()
	parent_size = dict()
	for i in range(1, n + 1):
		parent_tree[i] = i
		parent_size[i] = 1
	for (index, i) in enumerate(children, 1):
		(a, b) = equal(index, i, parent_tree)
		if a != b:
			parent_tree[b] = a
			parent_size[a] += parent_size[b]
	ans = []
	for (index, i) in enumerate(children, 1):
		ans.append(parent_size[to_root(index, parent_tree)])
	print(' '.join([str(i) for i in ans]))


t = int(input())
for test in range(t):
	n = int(input())
	p = [int(x) for x in input().split()]
	cov = {}
	for i in range(n):
		if i + 1 not in cov:
			lenn = 1
			in_bet = set()
			in_bet.add(i + 1)
			j = p[i]
			while j != i + 1:
				in_bet.add(j)
				lenn += 1
				j = p[j - 1]
			for ch in list(in_bet):
				cov[ch] = lenn
	for i in sorted(list(cov.keys())):
		print(cov[i], end=' ')
	print()


t = int(input())
import sys
input = sys.stdin.readline
while t > 0:
	t -= 1
	n = int(input())
	a = [int(x) for x in input().split()]
	v = [0 for i in range(n + 1)]
	count = [1 for i in range(n + 1)]
	k = 1
	for i in range(n):
		if v[i + 1] == 0:
			v[i + 1] = k
			j = a[i]
			v[j] = k
			while j != i + 1:
				j = a[j - 1]
				v[j] = k
				count[k] += 1
		k += 1
	for i in range(n):
		print(count[v[i + 1]], end=' ')
	print()


import sys
input = sys.stdin.readline

def calc(n, arr, i):
	turns = 0
	origin = i
	cur = arr[i]
	while cur != origin:
		cur = arr[cur]
		turns += 1
	return turns + 1
q = int(input())
for _ in range(q):
	n = int(input())
	arr = list(map(lambda x: int(x) - 1, input().split()))
	print(*[calc(n, arr, i) for i in range(n)])


t = int(input())

def when(i, h):
	if h == i:
		return 1
	v[i] = True
	return when(i, p[h]) + 1
for _ in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	p = [i - 1 for i in p]
	ans = [1 for i in range(n)]
	v = [False for i in range(n)]
	for i in range(n):
		if v[i]:
			continue
		ans[i] = when(i, p[i])
	print(*ans)


def main():
	n = int(input())
	s = list(map(int, input().split()))
	for i in range(len(s)):
		k = 0
		t = s[i]
		while t != s[i] or k == 0:
			t = s[t - 1]
			k += 1
		print(k, end=' ')
	print()
	return 0
a = int(input())
for i in range(a):
	main()


for w in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	l = [0] * n
	for i in range(n):
		if l[i] == 0:
			count = 1
			j = p[i] - 1
			while j != i:
				count += 1
				j = p[j] - 1
			l[i] = count
			j = p[i] - 1
			while j != i:
				l[j] = count
				j = p[j] - 1
	for i in range(n):
		print(l[i], end=' ')
	print()


q = int(input())
for _ in range(q):
	n = int(input())
	p = list(map(int, input().split()))
	ans = []
	for i in range(n):
		if p[i] == i + 1:
			ans.append(1)
		else:
			c = 1
			temp = p[i]
			while temp != i + 1:
				temp = p[temp - 1]
				c += 1
			ans.append(c)
	print(*ans)


import array
import math
import os
import sys

def main():
	Q = read_int()
	for _ in range(Q):
		N = read_int()
		P = [x - 1 for x in read_ints()]
		print(*solve(N, P))

def solve(N, P):
	ans = [0] * N
	for i in range(N):
		if ans[i] != 0:
			continue
		s = set()
		x = i
		while x not in s:
			s.add(x)
			x = P[x]
		for x in s:
			ans[x] = len(s)
	return ans
DEBUG = 'DEBUG' in os.environ

def inp():
	return sys.stdin.readline().rstrip()

def read_int():
	return int(inp())

def read_ints():
	return [int(e) for e in inp().split()]

def dprint(*value, sep=' ', end='\n'):
	if DEBUG:
		print(*value, sep=sep, end=end)
main()


import sys
import os
from io import IOBase, BytesIO
import math
mod = 10 ** 9 + 7
pie = 3.1415926536

def modinv(n, p):
	return pow(n, p - 2, p)

def ncr(n, r, p):
	t = fact[n] * (ifact[r] * ifact[n - r] % p) % p
	return t

def ain():
	return list(map(int, sin().split()))

def sin():
	return input().strip()

def GCD(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def read2DIntArray(row, col):
	arr = []
	for i in range(0, row):
		temp = list(map(int, sin().split()))
		arr.append(temp)
	return arr

def read2DCharArray(row, col):
	arr = []
	for i in range(0, row):
		temp = str(sin())
		arr.append(temp)
	return arr

def smallestNumber(n):
	lst = list(str(n))
	lst.sort()
	tmp = ''
	for (i, n) in enumerate(lst):
		if n != '0':
			tmp = lst.pop(i)
			break
	return str(tmp) + ''.join(lst)

def SieveOfEratosthenes(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * 2, n + 1, p):
				prime[i] = False
		p += 1
	prime[0] = False
	prime[1] = False
	lst = []
	for p in range(n + 1):
		if prime[p]:
			lst.append(p)
	return lst

def nCr(n, r):
	a = 1
	b = 1
	c = 1
	for i in range(1, n + 1):
		c *= i
	for i in range(1, r + 1):
		b *= i
	for i in range(1, n - r + 1):
		a *= i
	return c // (a * b)

def sieveOfEratosthenes1(N, s):
	prime = [False] * (N + 1)
	for i in range(2, N + 1, 2):
		s[i] = 2
	for i in range(3, N + 1, 2):
		if prime[i] == False:
			s[i] = i
			for j in range(i, int(N / i) + 1, 2):
				if prime[i * j] == False:
					prime[i * j] = True
					s[i * j] = i

def generatePrimeFactors(N):
	s = [0] * (N + 1)
	sieveOfEratosthenes1(N, s)
	curr = s[N]
	cnt = 1
	factors = []
	power = []
	while N > 1:
		N //= s[N]
		if curr == s[N]:
			cnt += 1
			continue
		factors.append(curr)
		power.append(cnt)
		curr = s[N]
		cnt = 1
	return (factors, power)

def main():
	for _ in range(int(sin())):
		n = int(sin())
		p = ain()
		for i in range(n):
			p[i] -= 1
		res = [-1] * n
		for i in range(n):
			day = 0
			x = p[i]
			while x != i:
				x = p[x]
				day += 1
			res[i] = day + 1
		print(*res)
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.getvalue())
			(self.truncate(0), self.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			self.write = lambda s: self.buffer.write(s.encode('ascii'))
			self.read = lambda : self.buffer.read().decode('ascii')
			self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')
main()


for i in range(int(input())):
	n = int(input())
	p = list(map(lambda x: x - 1, map(int, input().split())))
	lis = []
	for q in range(n):
		lis.append(0)
	for starting in range(n):
		if lis[starting] == 0:
			current = p[starting]
			count = 1
			while current != starting:
				count += 1
				current = p[current]
			lis[starting] = count
			current = p[starting]
			while current != starting:
				lis[current] = count
				current = p[current]
	print(' '.join(map(str, lis)))


import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
for tc in range(int(input())):
	(n,) = I()
	l = [int(i) - 1 for i in input().split()]
	p = [i for i in range(n)]
	v = [0] * n
	for i in range(n):
		if not v[i]:
			v[i] = 1
			j = l[i]
			while not v[j]:
				v[j] = 1
				v[i] += 1
				p[j] = i
				j = l[j]
	for i in range(n):
		print(v[p[i]], end=' ')
	print()


import math

def main():
	queries = int(input())
	for _ in range(queries):
		count = int(input())
		books = list(map(int, input().split()))
		books = [n - 1 for n in books]
		answer = [-1] * count
		for i in range(count):
			days = 1
			book_initially_at = books[i]
			current_book_at = books[books[i]]
			while book_initially_at != current_book_at:
				current_book_at = books[current_book_at]
				days += 1
			answer[i] = days
		print(*answer)
main()


for _ in range(int(input())):
	n = int(input())
	a = [int(i) - 1 for i in input().split()]
	c = [1] * n
	b = set()
	for i in range(n):
		if a[i] in b:
			continue
		if len(b) == n:
			break
		j = i
		a1 = set()
		s = 1
		while a[j] != i:
			a1.add(a[j])
			b.add(a[j])
			s += 1
			j = a[j]
		for k in a1:
			c[k] = s
	print(*c)


import sys
import math
input = sys.stdin.readline
for test in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [0] * n
	for j in range(1, n + 1):
		if ans[j - 1]:
			continue
		same = [j]
		cnt = 1
		t = a[j - 1]
		while t != j:
			same.append(t)
			cnt += 1
			t = a[t - 1]
		for j in same:
			ans[j - 1] += cnt
	print(*ans)


from sys import stdin
q = int(stdin.readline().rstrip())
for _ in range(q):
	n = int(stdin.readline().rstrip())
	data = [int(x) for x in stdin.readline().rstrip().split()]
	ans = [0] * n
	for i in range(n):
		now = i + 1
		route = [i]
		cnt = 1
		nex = data[i]
		if ans[i]:
			continue
		while True:
			route.append(nex - 1)
			if nex == now:
				break
			nex = data[nex - 1]
			cnt += 1
		for j in route:
			ans[j] = cnt
	print(*ans)


for i in range(int(input())):
	x = int(input())
	p = list(map(int, input().split()))
	for j in range(x):
		(tmp, num) = (j, 1)
		while p[tmp] - 1 != j:
			tmp = p[tmp] - 1
			num += 1
		print(num, end=' ')
	print()


t = int(input(''))
for _ in range(t):
	n = int(input(''))
	p = list(map(int, input('').split(' ')))
	d = {}
	for i in range(n):
		d[p[i]] = i + 1
	exp = [False] * (n + 1)
	ans = {}
	for i in range(1, n + 1, 1):
		if not exp[i]:
			a = [i]
			c = 1
			t = i
			while d[t] != i:
				t = d[t]
				exp[t] = True
				c = c + 1
				a.append(t)
			for f in a:
				ans[f] = c
	for i in range(1, n + 1, 1):
		print(ans[i], end=' ')
	print('')


from sys import stdin, stdout
from collections import defaultdict
q = int(input())
for _ in range(q):
	n = int(input())
	nums = list(map(int, stdin.readline().strip().split()))
	nums = [0] + nums
	ans = []
	visited = defaultdict(int)
	for i in nums[1:]:
		if not visited[i]:
			count = 1
			found = nums[i]
			cycle = [i, found]
			while found != i:
				found = nums[found]
				count += 1
				cycle.append(found)
			for el in cycle:
				visited[el] = count
			ans.append(count)
		else:
			ans.append(visited[i])
	print(*ans)


q = int(input())
for i in range(q):
	n = int(input())
	p = list(map(int, input().split()))
	m = [1] * n
	for j in range(n):
		if m[p[j] - 1] == 1:
			min_m = {}
			last = j
			min_m[j] = j
			while p[min_m[last]] - 1 not in min_m:
				min_m[p[min_m[last]] - 1] = p[min_m[last]] - 1
				last = p[min_m[last]] - 1
			for k in min_m:
				m[k] = len(min_m.keys())
	for k in m:
		print(k, end=' ')
	print('')


def write_cycles(cycle_times, trace, counter):
	for point in trace:
		cycle_times[point - 1] = counter

def find_answer(lst):
	n = len(lst)
	answers = [0] * n
	cycle_time = [-1] * n
	for i in range(n):
		if cycle_time[i] > -1:
			answers[i] = cycle_time[i]
			continue
		start = i + 1
		curr = start
		trace = []
		counter = 0
		while True:
			counter += 1
			trace.append(curr)
			curr = lst[curr - 1]
			if curr == start:
				answers[i] = counter
				write_cycles(cycle_time, trace, counter)
				break
	return answers
q = int(input())
for _ in range(q):
	n = int(input())
	ls = list(map(int, input().split()))
	answers = find_answer(ls)
	print(' '.join(map(str, answers)))


try:

	def fun(n, l):
		for j in range(n):
			l[j] -= 1
		lst = []
		for i in l:
			p = i
			c = 1
			a = l[i]
			while a != p:
				c += 1
				a = l[a]
			lst.append(c)
		return lst
	t = int(input())
	for _ in range(t):
		n = int(input())
		l = list(map(int, input().split()))
		ans = fun(n, l)
		print(*ans)
except:
	pass


import sys
line_count = 0
for line in sys.stdin.readlines():
	inputs = line.split()
	if line_count == 0:
		q = int(inputs[0])
	elif line_count % 2 == 1:
		n = int(inputs[0])
	elif line_count % 2 == 0:
		p = []
		for i in range(n):
			p.append(int(inputs[i]))
		cycles = []
		seen = [False for i in range(n)]
		for i in range(n):
			element = i + 1
			if seen[element - 1]:
				continue
			seen[element - 1] = True
			new = element
			cyc = [element]
			while True:
				new = p[new - 1]
				if new == element:
					break
				seen[new - 1] = True
				cyc.append(new)
			cycles.append(cyc)
		answer = [0 for i in range(n)]
		for cyc in cycles:
			len_cyc = len(cyc)
			for element in cyc:
				answer[element - 1] = len_cyc
		for i in answer:
			print(i, end=' ')
		print('')
	if line_count == 2 * q:
		break
	line_count += 1


for _ in range(int(input())):
	n = int(input())
	p = [0] + list(map(int, input().split()))
	d = {}
	visited = [0] * (n + 1)
	for i in range(1, n + 1):
		if not visited[i]:
			pos = p[i]
			visited[i] = 1
			cycle = [i]
			ans = 1
			while pos != i:
				visited[pos] = 1
				cycle.append(pos)
				ans += 1
				pos = p[pos]
			for x in cycle:
				d[x] = ans
	for i in range(1, n + 1):
		print(d[i], end=' ')
	print()


import sys

def main():
	q = int(sys.stdin.readline())
	for _ in range(q):
		n = int(sys.stdin.readline())
		p = [int(x) for x in sys.stdin.readline().split(' ')]
		solns = {e: -1 for e in p}
		for e in p:
			if solns[e] != -1:
				continue
			cycle = [e]
			pos = p[e - 1]
			ans = 1
			while pos != e:
				cycle += [pos]
				ans += 1
				pos = p[pos - 1]
			for visited in cycle:
				solns[visited] = ans
		print(' '.join((str(solns[e]) for e in p)))
main()


for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	p1 = [[] for j in range(n)]
	d = [0 for j in range(n)]
	for j in range(n):
		p1[j] = [j + 1, p[j]]
	val = []
	j = 0
	li = [[] for j in range(n)]
	visited = [0 for j in range(n)]
	for i in range(n):
		j = i
		if visited[i] == 0:
			while 1:
				li[i].append(p1[j][0])
				visited[j] = 1
				x = j
				j = p1[j][1] - 1
				if j == i:
					break
	for j in range(n):
		if len(li[j]) != 0:
			for k in range(len(li[j])):
				d[li[j][k] - 1] = len(li[j])
	for j in range(n):
		print(d[j], end=' ')
	print('')


t = int(input())

class DisjSet:

	def __init__(self, n):
		self.rank = [1] * n
		self.parent = [i for i in range(n)]
		self.extra = []

	def find(self, x):
		if self.parent[x] != x:
			self.parent[x] = self.find(self.parent[x])
		return self.parent[x]

	def Union(self, x, y):
		xset = self.find(x)
		yset = self.find(y)
		if xset == yset:
			self.extra.append((x, y))
			return
		if self.rank[xset] < self.rank[yset]:
			self.parent[xset] = yset
		elif self.rank[xset] > self.rank[yset]:
			self.parent[yset] = xset
		else:
			self.parent[yset] = xset
			self.rank[xset] = self.rank[xset] + 1
for _ in range(t):
	n = int(input())
	obj = DisjSet(n)
	a = list(map(lambda x: int(x) - 1, input().split()))
	for i in range(n):
		obj.Union(i, a[i])
	hash = {}
	for i in range(n):
		rep = obj.find(i)
		if rep not in hash:
			hash[rep] = 0
		hash[rep] += 1
	ans = []
	for i in range(n):
		ans.append(hash[obj.find(i)])
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	a = [0] + list(map(int, input().split()))
	ans = []
	for i in range(1, n + 1):
		idx = i
		num = 1
		while a[idx] != i:
			num += 1
			idx = a[idx]
		ans.append(num)
	print(*ans)


for i in range(int(input())):
	n = int(input())
	l1 = list(map(int, input().split()))
	t = 0
	res = [0] * n
	for ii in range(1, n + 1):
		cycle = [ii]
		x = ii - 1
		count = 0
		if res[ii - 1] == 0:
			while t != ii:
				t = l1[x]
				cycle.append(t)
				x = t - 1
				count += 1
			for el in cycle:
				res[el - 1] = count
		ii += 1
	print(*res)


def solve():
	n = int(input())
	a = list(map(int, input().split()))
	a = [i - 1 for i in a]
	d = [0 for i in a]
	for i in range(n):
		if d[i] > 0:
			continue
		j = i
		le = 1
		while i != a[j]:
			j = a[j]
			le += 1
		d[i] = le
		j = i
		while i != a[j]:
			j = a[j]
			d[j] = le
	print(*d)

def main():
	t = 1
	t = int(input())
	for _ in range(t):
		solve()
main()


cc = int(input())
while cc > 0:
	cc -= 1
	ll = int(input())
	(*aa,) = map(int, input().split())
	bb = []
	for i in range(ll):
		if aa[i] != 0:
			c = [aa[i]]
			ind = aa[i] - 1
			aa[i] = 0
			while ind != i:
				c.append(aa[ind])
				z = ind
				ind = aa[ind] - 1
				aa[z] = 0
			bb.append(c)
	ans = []
	for i in range(ll):
		for b in bb:
			if i + 1 in b:
				ans.append(len(b))
				break
	print(*ans)


import os
import sys
from io import BytesIO, IOBase

def main():
	pass
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
t = int(input())
while t:
	n = int(input())
	l = [int(i) - 1 for i in input().split()]
	ans = [0] * n
	visited = [False] * n
	for i in range(n):
		cycle = []
		while not visited[i]:
			visited[i] = True
			i = l[i]
			cycle.append(i)
		for i in cycle:
			ans[i] = len(cycle)
	for i in ans:
		print(i, end=' ')
	print()
	t = t - 1


for t in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	for i in range(n):
		val = p[i]
		c = 1
		while i + 1 != val:
			val = p[val - 1]
			c += 1
		print(c, end=' ')
	print()


q = int(input())
for _ in range(q):
	n = int(input())
	P = [*map(int, input().split())]
	A = [-1] * len(P)
	for i in range(n):
		if A[i] != -1:
			continue
		cycle_len = 1
		j = P[i]
		while j - 1 != i:
			A[j - 1] = i
			cycle_len += 1
			j = P[j - 1]
		A[i] = -cycle_len
	print(' '.join([str(-x) if x < 0 else str(-A[x]) for x in A]))


Q = int(input())
for q in range(Q):
	N = int(input())
	P = list(map(int, input().split()))
	out = []
	i = 1
	for p in P:
		o = 1
		while p != i:
			p = P[p - 1]
			o += 1
		out.append(str(o))
		i += 1
	print(' '.join(out))


t = int(input())
while t:
	n = int(input())
	l = [int(i) - 1 for i in input().split()]
	for i in range(n):
		k = i
		count = 0
		flag = 0
		while k != i or flag == 0:
			flag = 1
			k = l[k]
			count += 1
		print(count, end=' ')
	print()
	t = t - 1


q = int(input())
for _ in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	u = [0 for i in range(len(a))]
	for i in range(len(a)):
		if u[a[i] - 1] == 0:
			l = 1
			b = a[i] - 1
			o = i
			while b != o:
				b = a[b]
				b -= 1
				l += 1
			z = a[i] - 1
			while u[z] == 0:
				u[z] = l
				z = a[z] - 1
	for i in range(len(a)):
		print(u[a[i] - 1], end=' ')
	print('')


def dfs(root, l):
	visited[root] = 1
	node = p[root] - 1
	if visited[node] == 0:
		l.append(node)
		dfs(node, l)
t = int(input())
while t > 0:
	n = int(input())
	p = list(map(int, input().split()))
	visited = [0] * n
	arr = [0] * n
	for i in range(n):
		l = []
		if visited[i] == 0:
			l.append(i)
			dfs(i, l)
			for i in l:
				arr[i] = len(l)
	for i in arr:
		print(i, end=' ')
	print()
	t -= 1


gh = ''
for _ in ' ' * int(input()):
	a = int(input())
	b = [0] + list(map(int, input().split()))
	z = [0] * (a + 1)
	for i in range(1, a + 1):
		if b[i] == i:
			gh += '1 '
		elif z[i] == 0:
			k = i
			s = 1
			while i != b[k]:
				z[b[k]] = i
				k = b[k]
				s += 1
			z[i] = s
			gh += str(s) + ' '
		else:
			gh += str(z[z[i]]) + ' '
	gh += '\n'
print(gh)


q = int(input())
for _ in range(q):
	n = int(input())
	it = list(map(int, input().split()))
	cu = [i + 1 for i in range(n)]
	ans = [10 ** 9 for i in range(n)]
	j = 1
	while 10 ** 9 in ans:
		cc = cu[:]
		for i in range(n):
			cu[it[i] - 1] = cc[i]
		for i in range(n):
			if cu[i] == i + 1:
				ans[i] = min(ans[i], j)
		j += 1
	print(*ans)


def day(i, s, f, d):
	if s[i - 1] == f:
		return d
	else:
		return day(s[i - 1], s, f, d + 1)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	x = []
	for t in a:
		x.append(day(t, a, t, 1))
	print(*x)


import sys
from collections import deque
input = sys.stdin.readline

def bfs(root):
	q = [root]
	q = deque(q)
	vis = [0] * n
	parent = [-1] * n
	while len(q) != 0:
		e = q.popleft()
		vis[e] = 1
		for i in graph[e]:
			if vis[i] == 0:
				q.append(i)
				parent[i] = e
			else:
				s = e
				path = [s]
				while parent[s] != -1:
					s = parent[s]
					path.append(s)
				return path
for nt in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	graph = [[] for i in range(n)]
	for i in range(n):
		graph[i].append(a[i] - 1)
	vis = [0] * n
	ans = [0] * n
	for i in range(n):
		if vis[i] == 0:
			p = bfs(i)
			for j in p:
				vis[j] = 1
				ans[j] = len(p)
	print(*ans)


q = int(input())

def main():
	n = int(input())
	ps = list(map(int, input().split()))
	ps = [p - 1 for p in ps]
	cnts = [-1] * n
	ans = 0
	for i in range(n):
		s = i
		if cnts[i] > -1:
			continue
		cnt = 1
		n_list = [s]
		n = ps[s]
		while s != n:
			cnt += 1
			n = ps[n]
			n_list.append(n)
		for l in n_list:
			cnts[l] = cnt
	print(*cnts)
for _ in range(q):
	main()


q = int(input())
for i in range(q):
	n = int(input())
	s = list(map(int, input().split()))
	used = [0 for i in range(n)]
	ways = [0 for i in range(n)]
	for j in range(n):
		m = j
		while not used[j]:
			m = s[m] - 1
			used[m] = 1
			ways[j] += 1
		m = j
		while used[j] == 1:
			m = s[m] - 1
			used[m] = 2
			ways[m] = ways[j]
	for j in ways:
		print(j, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	result = [-1] * (n + 1)
	for i in range(n):
		if result[i + 1] != -1:
			continue
		(x, y, cnt) = (-1, i + 1, 0)
		visited = []
		while x != i + 1:
			x = a[y - 1]
			y = x
			cnt += 1
			visited.append(x)
		for child in visited:
			result[child] = cnt
	for i in range(1, n + 1):
		print(result[i], end=' ')
	print()


from sys import stdin

def countDays(nums, f, to, memo):
	ans = 0
	if f != to and memo[f][to] == -1:
		ans = 1 + countDays(nums, nums[f], to, memo)
	memo[f][to] = ans
	return memo[f][to]

def main():
	querys = int(stdin.readline())
	for query in range(querys):
		n = int(stdin.readline())
		nums = list(map(int, stdin.readline().strip().split()))
		for i in range(n):
			nums[i] -= 1
		memo = [[-1 for _ in range(n)] for _ in range(n)]
		ans = [1 + countDays(nums, nums[x], x, memo) for x in range(n)]
		print(*ans)
main()


q = int(input())
for _ in range(q):
	n = int(input())
	a = list((i for i in range(n)))
	p = list(map(int, input().split()))
	res = [0] * n
	while a:
		(i, k) = (a[0], a[0])
		d = 0
		temp = []
		while p[i] != k + 1:
			d += 1
			i = p[i] - 1
			a.remove(i)
			temp.append(i)
		d += 1
		i = p[i] - 1
		a.remove(i)
		temp.append(i)
		for i in temp:
			res[i] = d
	for j in res:
		print(j, end=' ')


num_queries = int(input())
for _ in range(num_queries):
	num_kids = int(input())
	book_gifts = tuple(map(int, input().split()))
	return_times = [9999 for _ in range(num_kids)]
	original_books = list(range(num_kids))
	new_books = [0 for _ in range(num_kids)]
	for iteration in range(num_kids):
		for (i, gift) in enumerate(original_books):
			new_books[book_gifts[i] - 1] = gift
		for (i, new_book) in enumerate(new_books):
			if new_book == i:
				return_times[i] = min(return_times[i], iteration + 1)
		original_books = new_books[:]
	print(' '.join(map(str, return_times)))


def r():
	return map(int, input().split())
t = int(input())
for _ in range(t):
	n = int(input())
	l = list(r())
	m = {}
	for i in range(1, n + 1):
		m[i] = l[i - 1]
	tab = [0] * n
	for i in range(1, n + 1):
		c = 1
		f = m[i]
		if tab[i - 1] == 0:
			cp = [f]
			while f != i:
				c += 1
				f = m[f]
				cp.append(f)
			for v in cp:
				tab[v - 1] = c
	print(*tab)


from sys import stdin
from collections import deque
from math import sqrt, floor, ceil, log, log2, log10, pi

def ii():
	return int(stdin.readline())

def fi():
	return float(stdin.readline())

def mi():
	return map(int, stdin.readline().split())

def fmi():
	return map(float, stdin.readline().split())

def li():
	return [x for x in mi()]

def si():
	return stdin.readline()
for _ in range(ii()):
	ans = []
	n = ii()
	a = li()
	for i in range(n):
		j = i
		x = 1
		while a[j] != i + 1:
			x += 1
			j = a[j] - 1
		ans.append(x)
	print(*ans)


def gt(x, l, y):
	if l[x - 1] == y:
		return 1
	else:
		return 1 + gt(l[x - 1], l, y)
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	res = []
	for i in range(1, n + 1):
		res.append(gt(i, l, i))
	print(*res)


case = int(input())
for _ in range(case):
	n = int(input())
	p = list(map(int, input().split()))
	d = []
	for i in range(1, n + 1):
		t = i
		cnt = 1
		while i != p[t - 1]:
			cnt += 1
			t = p[t - 1]
		d.append(cnt)
	print(*d)


t = int(input())
while t:
	t -= 1
	n = int(input())
	a = list(map(int, input().split()))
	for i in range(0, n):
		if i + 1 == a[i]:
			print(1, end=' ')
			continue
		k = a[i]
		sum = 1
		while k != i + 1:
			l = a[k - 1]
			k = l
			sum += 1
		print(sum, end=' ')
	print()


t = int(input())
for z in range(t):
	n = int(input())
	p = list(map(int, input().rstrip().split()))
	if len(p) == 1:
		print(p[0], end=' ')
	else:
		for i in range(len(p)):
			count = 1
			k = p[i]
			j = i
			while p[j] - 1 != i:
				count += 1
				j = p[j] - 1
			print(count, end=' ')
	print()


import sys
input = sys.stdin.buffer.readline

class UnionFind:

	def __init__(self, n):
		self.n = n
		self.root = [-1] * (n + 1)
		self.rnk = [0] * (n + 1)

	def Find_Root(self, x):
		if self.root[x] < 0:
			return x
		else:
			self.root[x] = self.Find_Root(self.root[x])
			return self.root[x]

	def Unite(self, x, y):
		x = self.Find_Root(x)
		y = self.Find_Root(y)
		if x == y:
			return
		elif self.rnk[x] > self.rnk[y]:
			self.root[x] += self.root[y]
			self.root[y] = x
		else:
			self.root[y] += self.root[x]
			self.root[x] = y
			if self.rnk[x] == self.rnk[y]:
				self.rnk[y] += 1

	def isSameGroup(self, x, y):
		return self.Find_Root(x) == self.Find_Root(y)

	def Count(self, x):
		return -self.root[self.Find_Root(x)]
N = int(input())
for _ in range(N):
	n = int(input())
	a = list(map(int, input().split()))
	res = []
	uf = UnionFind(n)
	for i in range(n):
		uf.Unite(a[i], i + 1)
	for i in range(n):
		res.append(uf.Count(i + 1))
	print(*res)


testes = int(input())
for t in range(testes):
	n = int(input())
	p = list(map(int, input().split(' ')))
	visit = [0 for k in range(n)]
	sets = []
	for k in range(n):
		atual = p[k]
		index = k
		l = set()
		if visit[index] == 1:
			continue
		while visit[index] == 0:
			l.add(index)
			visit[index] = 1
			index = atual - 1
			atual = p[index]
		if len(l) > 0:
			sets.append(l)
	for i in range(n - 1):
		atual = set()
		atual.add(i)
		for j in sets:
			if atual.isdisjoint(j):
				continue
			else:
				print(len(j), end=' ')
				break
	atual = set()
	atual.add(n - 1)
	for j in sets:
		if atual.isdisjoint(j):
			continue
		else:
			print(len(j))
			break


def lower_index(n):
	return n - 1
n_queries = int(input())
for _ in range(n_queries):
	n_children = int(input())
	routine = map(int, input().split())
	routine = list(map(lower_index, routine))
	done = []
	cycle_lengths = [0 for _ in range(n_children)]
	for child in range(n_children):
		if child not in done:
			cycle_found = False
			cycle_length = 0
			cur_holder = child
			prev_holders = []
			while not cycle_found:
				prev_holders.append(cur_holder)
				cur_holder = routine[cur_holder]
				cycle_length += 1
				if cur_holder in prev_holders:
					cycle_found = True
			for _child in prev_holders:
				done.append(_child)
				cycle_lengths[_child] = cycle_length
	print(' '.join(list(map(str, cycle_lengths))))


q = int(input())
for kek in range(q):
	n = int(input())
	p = list(map(int, input().split()))
	a = [0]
	ans = [0]
	for i in p:
		a.append(i)
		ans.append(-1)
	total = set(range(1, n + 1))
	j = 1
	z = 0
	while len(total) > 0:
		if ans[j] > 0:
			for i in total:
				j = i
				break
			z = 0
		elif ans[j] == -2:
			ans[j] = z
			j = a[j]
			total.discard(j)
		else:
			z += 1
			ans[j] = -2
			j = a[j]
	print(*ans[1:])


for i in range(int(input())):
	n = int(input())
	l = list(map(lambda x: int(x) - 1, input().split()))
	ans = [0] * n
	for i in range(n):
		o = i
		k = []
		if ans[i] == 0:
			k.append(i)
			while l[o] != i:
				o = l[o]
				k.append(o)
			for z in k:
				ans[z] = len(k)
	print(' '.join([str(z) for z in ans]))


q = int(input())
for _ in range(q):
	_ = int(input())
	arr = list(map(int, input().split()))
	arr2 = [0 for _ in range(len(arr))]
	for i in range(1, len(arr) + 1):
		new = []
		if arr2[i - 1] == 0:
			k = arr[i - 1]
			sch = 1
			new.append(k)
			while k != i:
				k = arr[k - 1]
				new.append(k)
				sch += 1
			for el in new:
				arr2[el - 1] += len(new)
	for i in arr2:
		print(i)


for _ in range(int(input())):
	n = int(input())
	l = [0] + [int(x) for x in input().split()]
	ans = [0] * (n + 1)
	cycle = {}
	for i in range(1, n + 1):
		if ans[i] != 0:
			continue
		s = set([i])
		if i == l[i]:
			ans[i] = 1
		else:
			j = i
			while True:
				ans[i] += 1
				s.add(l[j])
				if i == l[j]:
					break
				j = l[j]
		for j in list(s):
			ans[j] = len(s)
	print(*ans[1:])


def func(i, c, main):
	if p[i] - 1 == main:
		return c
	else:
		return func(p[i] - 1, c + 1, main)
q = int(input())
for qq in range(0, q):
	n = int(input())
	p = [int(x) for x in input().split()]
	res = []
	for i in range(0, n):
		res.append(func(i, 1, i))
	print(*res)


q = int(input())
for _ in range(q):
	n = int(input())
	p = list(map(int, input().strip().split()))
	d = {i + 1: p[i] for i in range(n)}
	l = [0] * n
	v = [0] * n
	for i in range(n):
		if v[i] != 0:
			continue
		j = int(i + 1)
		c = 1
		s = set()
		while i + 1 != d[j]:
			s.add(d[j])
			j = d[j]
			c += 1
			v[j - 1] = 1
		l[i] = c
		for x in s:
			l[x - 1] = c
	print(*l)


for i in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	w = [0] * n
	ans2 = [1] * n
	for j in range(n):
		if w[j] == 1:
			continue
		s = set()
		s.add(j)
		t = j
		w[t] = 1
		ans = 0
		while l[t] - 1 != j:
			t = l[t] - 1
			ans += 1
			s.add(t)
			w[t] = 1
		for j in s:
			ans2[j] += ans
	print(*ans2, sep=' ')


for k in range(int(input())):
	n = int(input())
	ls = list(map(int, input().split()))
	ary = [-1] * n
	for i in range(len(ls)):
		if ary[i] != -1:
			continue
		cnt = 1
		val = ls[i] - 1
		valls = [i]
		while val != i:
			cnt += 1
			valls.append(val)
			val = ls[val] - 1
		for j in range(len(valls)):
			ary[valls[j]] = cnt
	print(*ary)


q = int(input())
nums = []
pos = []
for _ in range(q):
	nums += [int(input())]
	p = input().split()
	pos += [[int(x) - 1 for x in p]]
for i in range(q):
	n = nums[i]
	p = pos[i]
	list1 = list(range(n))
	list2 = []
	dict = dict.fromkeys(list(range(n)), 0)
	for i in list1:
		if i == 'a':
			continue
		j = p[i]
		count = 1
		while j != i:
			j = p[j]
			count += 1
		j = p[i]
		dict[i] = count
		while j != i:
			list1[j] = 'a'
			dict[j] = count
			j = p[j]
	for key in dict.keys():
		print(dict[key], end=' ')


q = int(input())
for x in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	sets = []
	sett = []
	visited = [0] * n
	ind = 0
	visited[0] = 1
	sett = [1]
	while True:
		x = a[ind]
		if not visited[x - 1]:
			sett.append(x)
			visited[x - 1] = 1
			ind = x - 1
		else:
			sets.append(sett)
			flag = 0
			for i in range(n):
				if not visited[i]:
					flag = 1
					ind = i
					sett = [i + 1]
					visited[i] = True
					break
			if flag == 0:
				break
	days = [0] * n
	for i in range(len(sets)):
		for j in range(len(sets[i])):
			days[sets[i][j] - 1] = str(len(sets[i]))
	print(' '.join(days))


for _ in range(int(input())):
	n = int(input())
	nums = list(map(int, input().split()))
	days = []
	for i in range(n):
		this = i
		day = 0
		while True:
			day += 1
			if nums[this] == i + 1:
				days.append(day)
				break
			this = nums[this] - 1
	print(' '.join(list(map(str, days))))


for _ in range(int(input())):
	n = int(input())
	d = [int(i) for i in input().split()]
	a = {}
	for i in range(n):
		a[i + 1] = d[i]
	ans = {}
	count = {}
	for i in range(1, n + 1):
		if a[i] not in count.keys():
			j = a[i]
			temp = (i,)
			c = 1
			count[i] = 0
			while j != i:
				temp += (j,)
				j = a[j]
				c += 1
				count[j] = 0
			ans[temp] = c
	fans = {}
	ansk = list(ans.keys())
	for i in range(len(ans)):
		for j in range(len(ansk[i])):
			fans[ansk[i][j]] = ans[ansk[i]]
	final = []
	for i in range(1, n + 1):
		final.append(fans[i])
	print(*final)


def main():
	n = int(input())
	s = list(map(int, input().split()))
	j = 0
	l = set()
	g = [[]]
	for i in range(len(s)):
		k = 0
		t = s[i]
		while t != s[i] or (k == 0 and t not in l):
			t = s[t - 1]
			k += 1
			l.add(t)
			g[j].append(t)
		g.append([])
		j += 1
	ans_1 = []
	for i in g:
		if i != []:
			ans_1.append(i)
	ans_2 = [0 for i in range(n)]
	for i in range(len(ans_1)):
		for g in range(len(ans_1[i])):
			ans_2[ans_1[i][g] - 1] = len(ans_1[i])
	print(*ans_2)
	return 0
a = int(input())
for i in range(a):
	main()


q = int(input())
for i in range(q):
	n = int(input())
	p = list((int(i) - 1 for i in input().split()))
	used = [0] * n
	ans = [0] * n
	for j in range(n):
		if not used[j]:
			cur = []
			while not used[j]:
				cur.append(j)
				used[j] = True
				j = p[j]
			for _ in cur:
				ans[_] = len(cur)
	for j in range(n):
		print(ans[j], end=' ')


def search(kid, n, p, dic):
	days = 1
	persons = [kid]
	current_p = p[kid - 1]
	for i in range(n):
		if kid == current_p:
			for person in persons:
				dic[person] = days
			break
		persons.append(current_p)
		current_p = p[current_p - 1]
		days += 1
q = int(input())
for _ in range(q):
	dic = {}
	n = int(input())
	p = list(map(int, input().split(' ')))
	for i in range(1, n + 1):
		if i not in dic:
			search(i, n, p, dic)
	for i in range(1, n + 1):
		print(dic[i], end=' ')
	print('')


for _ in range(int(input())):
	n = int(input())
	a = list(map(lambda a: int(a) - 1, input().split()))
	ans = [0 for _ in range(n)]
	for i in range(n):
		if not ans[i]:
			cycle = [i]
			x = i
			while a[x] != i:
				x = a[x]
				cycle.append(x)
			for x in cycle:
				ans[x] = len(cycle)
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	for x in range(n):
		count = 0
		y = x
		while True:
			y = a[y] - 1
			count += 1
			if x == y:
				break
		print(count, end=' ')
	print('')


def main():
	n = int(input())
	l = [int(x) - 1 for x in input().split()]
	ans = [-1] * n
	for i in range(n):
		if ans[i] > 0:
			continue
		q = [i]
		while l[q[-1]] != q[0]:
			q.append(l[q[-1]])
		c = len(q)
		for x in q:
			ans[x] = c
	print(' '.join(map(str, ans)))
	return
q = int(input())
for _ in range(q):
	main()


def arr_inp():
	return [int(x) for x in input().split()]
for i in range(int(input())):
	(n, p, ans, dic) = (int(input()), arr_inp(), [], dict())
	p.insert(0, 0)
	for j in range(1, n + 1):
		(tem, c, ext) = (p[p[j]], 1, [])
		if p[j] not in dic:
			while tem != p[j]:
				ext.append(tem)
				tem = p[tem]
				c += 1
		else:
			c = dic[p[j]]
		for i in ext:
			dic[i] = c
		ans.append(c)
	print(*ans)


t = int(input())
for case_num in range(t):
	n = int(input())
	a = list(map(int, input().split(' ')))
	vis = [False for i in range(n + 1)]
	day = [0 for i in range(n + 1)]
	for i in range(1, n + 1):
		if vis[i]:
			continue
		vis[i] = True
		cnt = 1
		path = set()
		path.add(i)
		curr = a[i - 1]
		while curr != i:
			vis[curr] = True
			path.add(curr)
			curr = a[curr - 1]
			cnt += 1
		for step in path:
			day[step] = cnt
	print(' '.join(map(str, day[1:])))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	sol = [1] * n
	for i in range(n):
		k = a[i] - 1
		nosteps = 1
		while k != i:
			k = a[k] - 1
			nosteps += 1
		sol[i] = nosteps
	print(*sol)


T = int(input())
while T > 0:
	n = int(input())
	p = [int(i) - 1 for i in input().split()]
	ans = [0] * n
	visited = [False] * n
	visited_count = 0
	for i in range(0, n):
		if p[i] == i:
			ans[i] = 1
			visited[i] = True
			visited_count += 1
		elif visited[i] == False:
			next = p[i]
			count = 1
			visited[next] = True
			temp_arr = [next]
			while next != i:
				next = p[next]
				count += 1
				visited[next] = True
				visited_count += 1
				temp_arr.append(next)
			for j in temp_arr:
				ans[j] = count
			if visited_count == n:
				break
	for i in range(0, len(ans)):
		print(ans[i], end=' ')
	print()
	T -= 1


from sys import stdin, stdout
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	a = [0] + list(map(int, stdin.readline().split()))
	vis = [0] * (1 + n)
	for i in range(1, n + 1):
		if vis[i]:
			continue
		src = a[i]
		des = i
		sz = 1
		ll = []
		while src != des:
			ll += [src]
			src = a[src]
			sz += 1
		for ind in ll:
			a[ind] = sz
			vis[ind] = 1
		a[i] = sz
	print(*a[1:])


t = int(input())
while t:
	n = int(input())
	l = [int(i) - 1 for i in input().split()]
	ans = [0] * n
	visited = [False] * n
	for i in range(n):
		cycle = []
		while not visited[i]:
			visited[i] = True
			i = l[i]
			cycle.append(i)
		for i in cycle:
			ans[i] = len(cycle)
	for i in ans:
		print(i, end=' ')
	print()
	t = t - 1


q = int(input())
for t in range(q):
	n = int(input())
	l = [int(i) for i in input().split(' ')]
	flag = True
	d = dict()
	for i in range(1, len(l) + 1):
		d[i] = 0
	for i in range(1, len(l) + 1):
		if d[i] == 0:
			ll = []
			j = l[i - 1]
			count = 1
			ll.append(i)
			while j != i:
				ll.append(j)
				j = l[j - 1]
				count += 1
			for k in ll:
				d[k] = count
	for i in d.keys():
		print(d[i], end=' ')
	print()


nq = int(input())
iters = 0
while iters < nq:
	iters += 1
	nkids = input()
	kids = list(map(int, input().split()))
	idx = 0
	for kid in kids:
		idx = kid - 1
		days = 1
		while kids[idx] != kid:
			days += 1
			idx = kids[idx] - 1
		print('{} '.format(days), end='')
	print()


class DisjointSetUnion:

	def __init__(self, n):
		self.parent = list(range(n))
		self.size = [1] * n
		self.num_sets = n

	def find(self, a):
		acopy = a
		while a != self.parent[a]:
			a = self.parent[a]
		while acopy != a:
			(self.parent[acopy], acopy) = (a, self.parent[acopy])
		return a

	def union(self, a, b):
		(a, b) = (self.find(a), self.find(b))
		if a != b:
			if self.size[a] < self.size[b]:
				(a, b) = (b, a)
			self.num_sets -= 1
			self.parent[b] = a
			self.size[a] += self.size[b]

	def set_size(self, a):
		return self.size[self.find(a)]

	def __len__(self):
		return self.num_sets
for _ in range(int(input())):
	n = int(input())
	dsu = DisjointSetUnion(n + 1)
	for (i, pi) in enumerate(map(int, input().split())):
		dsu.union(i + 1, pi)
	print(*(dsu.set_size(i) for i in range(1, n + 1)))


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	g = list()
	for x in range(n):
		cnt = 1
		a = x
		while l[a] != x + 1:
			a = l[a] - 1
			cnt += 1
		g.append(cnt)
	print(*g)


def show_ciclu(x, a, answer):
	inceput = x
	nr = 0
	while True:
		nr += 1
		x = a[x]
		if x == inceput:
			break
	while True:
		answer[x] = nr
		x = a[x]
		if x == inceput:
			break
	return nr

def solve_test():
	n = int(input())
	a = [int(x) - 1 for x in input().split()]
	answer = [0 for _ in range(n)]
	for i in range(n):
		if answer[i] == 0:
			show_ciclu(i, a, answer)
	for i in answer:
		print(i, end=' ')
	print('')
t = int(input())
for _ in range(t):
	solve_test()


def findCircle(mass):
	start = mass[0]
	vect = [False] * len(mass)
	res = []
	d = {}
	s = {i - 1 for i in mass}
	while True:
		visited = []
		while not vect[start - 1]:
			vect[start - 1] = True
			s.remove(start - 1)
			visited.append(start)
			start = mass[start - 1]
		res.append(visited)
		if not s:
			break
		el = s.pop()
		start = mass[el]
		s.add(el)
	for item in res:
		for i in item:
			d[i] = len(item)
	return d
q = int(input())
for i in range(q):
	n = int(input())
	arr = list(map(int, input().split()))
	d = findCircle(arr)
	ans = []
	for i in range(1, n + 1):
		ans.append(str(d[i]))
	print(' '.join(ans))


t = int(input())
for i in range(t):
	n = int(input())
	lst = list(map(int, input().split()))
	ans = []
	for j in range(1, n + 1):
		idx = lst[j - 1]
		days = 1
		while j != idx:
			temp = lst[idx - 1]
			idx = temp
			days += 1
		ans.append(days)
	print(*ans)


import sys
q = int(input())
for _ in range(q):
	n = int(input())
	p = [int(x) for x in input().split()]
	r = [-1] * n
	for i in range(n):
		if r[i] == -1:
			l = [i + 1]
			cur = p[i]
			while l[0] != cur:
				l.append(cur)
				cur = p[cur - 1]
			for ind in l:
				r[ind - 1] = len(l)
	print(' '.join(map(str, r)))


m = int(input())
for _ in range(m):
	n = int(input())
	mas = list(map(int, input().split(' ')))
	for i in range(n):
		mas[i] -= 1

	def a(ind, num):
		res = 1
		while ind != num:
			num = mas[num]
			res += 1
		return res
	for i in range(n):
		print(a(i, mas[i]), end=' ')
	print()


t = int(input())

def solve(inn, val, count):
	while inn == val:
		return count
	return solve(inn, arr[val - 1], count + 1)
from collections import defaultdict
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().strip().split()))[:n]
	for num in arr:
		print(solve(num, arr[num - 1], 1), end=' ')
	print()


import sys
from collections import deque
readline = sys.stdin.readline
q = int(readline())
for _ in range(q):
	n = int(readline())
	p = [int(x) - 1 for x in readline().split()]
	s = [0 for _ in range(n)]
	myS = set()
	dd = dict()
	for i in range(n):
		if i in myS:
			continue
		k = i
		t = 1
		tmps = set()
		tmps.add(i)
		myS.add(i)
		while p[k] != i:
			k = p[k]
			t += 1
			if k not in myS:
				myS.add(k)
				tmps.add(k)
		for q in tmps:
			dd[q] = t
	for i in range(n):
		print(dd[i], end=' ')
	print()


for _ in range(int(input())):
	a = int(input())
	arr = list(map(int, input().split()))
	for i in range(len(arr)):
		c = 1
		ma = arr[arr[i] - 1]
		while ma != arr[i]:
			c += 1
			ma = arr[ma - 1]
		print(c, end=' ')


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	vis = [0 for i in range(n)]
	for i in range(n):
		if vis[i] == 0:
			path = set()
			path.add(i + 1)
			path.add(a[i])
			to = a[i]
			start = i + 1
			step = 1
			while to != start:
				to = a[to - 1]
				path.add(to)
				step += 1
			for i in path:
				vis[i - 1] = max(1, step)
	print(*vis, sep=' ')


q = int(input())
for i in range(q):
	n = int(input())
	arr = [int(j) - 1 for j in input().split(' ')]
	d = dict()
	for j in range(n):
		d[j] = 0
	for j in range(n):
		if d[j] == 0:
			a = []
			ind = j
			count = 0
			while j != arr[ind]:
				count += 1
				a.append(ind)
				ind = arr[ind]
			count += 1
			a.append(ind)
			for k in a:
				d[k] = count
	for j in range(n):
		print(d[j], end=' ')
	print()


q = int(input())
for _ in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [0] * n
	for i in range(n):
		if ans[i] != 0:
			continue
		c = a[i] - 1
		temp = [i]
		res = 1
		while a[c] != a[i]:
			temp.append(c)
			c = a[c] - 1
			res += 1
		for i in temp:
			ans[i] = res
	print(*ans)


import sys

def atoi(line):
	line = line.rstrip().split()
	return list(map(int, line))
ans = []
q = int(input())
for q_ in range(q):
	n = int(input())
	p = atoi(sys.stdin.readline())
	p.insert(0, 0)
	used = [False] * (n + 1)
	days = [1] * (n + 1)
	i = 1
	while i < n + 1:
		if used[i]:
			i += 1
			continue
		loop = [i]
		used[i] = True
		j = p[i]
		while j != loop[0]:
			j = p[j]
			loop.append(p[j])
			used[j] = True
		i += 1
		for k in loop:
			days[k] = len(loop)
	ans.append(days)
for d in ans:
	d = d[1:]
	print(*d, sep=' ')


hehe = int(input())
for i in range(hehe):
	n = int(input())
	check = [0] * n
	arr = list(map(int, input().split()))
	for j in range(len(arr)):
		if check[j] == 0:
			(hi, dem) = (j + 1, 0)
			while True:
				(check[hi - 1], hi) = (j + 1, arr[hi - 1])
				dem += 1
				if check[hi - 1] != 0:
					check[hi - 1] = dem
					print(dem, end=' ')
					break
		else:
			print(check[check[j] - 1], end=' ')


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	arr = arr
	f = [0] * n
	used = [False] * n
	for i in range(0, n):
		if not used[i]:
			v = arr[i] - 1
			ans = 1
			cycle = [i]
			while not used[v]:
				used[v] = True
				cycle.append(v)
				v = arr[v] - 1
			for el in cycle:
				f[el] = len(cycle) - 1
	print(*f)


ct = int(input())
for c in range(ct):
	n = int(input())
	li = [int(i) - 1 for i in input().split()]
	r = [-1 for i in range(n)]
	for i in range(n):
		if r[i] == -1:
			cont = 1
			aux = li[i]
			while aux != i:
				aux = li[aux]
				cont += 1
			aux = i
			for j in range(cont):
				r[aux] = cont
				aux = li[aux]
	print(*r)


a = int(input())
for i in range(a):
	n = int(input())
	b = []
	n1 = input().split(' ')
	for j in n1:
		b.append(int(j))
	for j in range(0, n):
		c = -1
		i = j
		k = 0
		while c != j:
			c = b[i] - 1
			i = c
			k += 1
		print(k, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	li = list(enumerate(list(map(int, input().split())), start=1))
	clusters = []
	vis = [0] * len(li)
	i = 0
	while i < len(li):
		if vis[i]:
			i += 1
		else:
			vis[i] = 1
			a = li[i][0] - 1
			c = [a]
			j = i
			while li[j][1] != a + 1:
				j = li[j][1] - 1
				vis[j] = 1
				c.append(j)
			clusters.append(c)
			i += 1
	ans = [0] * len(li)
	for c in clusters:
		l = len(c)
		for i in c:
			ans[i] = l
	print(*ans)


q = int(input())
queries = []
for i in range(q):
	n = int(input())
	string = input().split(' ')
	queries.append([int(num) for num in string])
for query in queries:
	result = []
	for i in range(len(query)):
		result.append('0')
	for i in range(len(query)):
		if result[i] == '0':
			allSteps = []
			totalSteps = 1
			index = query[i]
			while index != i + 1:
				allSteps.append(query[index - 1] - 1)
				index = query[index - 1]
				totalSteps += 1
			for step in allSteps:
				result[step] = str(totalSteps)
			result[i] = str(totalSteps)
	print(' '.join(result))


for i in [0] * int(input()):
	a = int(input())
	l1 = [0] * a
	l = list(map(int, input().split()))
	for x in l:
		ct = 1
		b = l[x - 1]
		while x != b:
			b = l[b - 1]
			ct += 1
		l1[l.index(x)] = ct
	print(*l1)


def arr_inp():
	return [int(x) for x in input().split()]
for i in range(int(input())):
	(n, p, ans) = (int(input()), arr_inp(), [])
	for j in range(n):
		(tem, c) = (p[p[j] - 1], 1)
		while tem != p[j]:
			tem = p[tem - 1]
			c += 1
		ans.append(c)
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	lis = [8] + list(map(int, input().split()))
	a = sorted(range(len(lis)), key=lambda k: lis[k])
	c = 1
	ans = []
	for i in range(1, n + 1):
		if lis[i] == i:
			ans.append(1)
			continue
		j = lis[i]
		while j != i:
			j = lis[j]
			c += 1
		ans.append(c)
		c = 1
	print(*ans)


import sys
for _ in range(int(input())):
	n = int(input())
	p = [int(i) for i in input().split()]
	final = [0] * n
	for i in range(n):
		if final[i] == 0:
			ans = 1
			val = []
			temp = p[i] - 1
			val.append(temp)
			while temp != i and ans <= n:
				temp = p[temp] - 1
				val.append(temp)
				ans += 1
			for k in val:
				final[k] = ans
		else:
			continue
	print(*final)


import sys
from collections import deque
input = sys.stdin.readline
n = int(input())

def clearLi(l):
	for i in range(0, len(li)):
		l[i] = 0
for i in range(n):
	m = int(input())
	li = [int(x) - 1 for x in input().split(' ')]
	newli = [0] * len(li)
	d = deque()
	currSum = 0
	currIndex = 0
	for i in range(m):
		if newli[i] == 0:
			currSum = 1
			d.clear()
			d.append(i)
			currIndex = li[i]
			while not currIndex == i:
				d.append(currIndex)
				currSum += 1
				currIndex = li[currIndex]
			for j in d:
				newli[j] = currSum
	print(*newli)


from collections import deque
import sys
sys.setrecursionlimit(5000)
t = int(input().rstrip())
for _ in range(t):
	no_boys = int(input().rstrip())
	books = list(map(int, input().rstrip().split()))
	i = 1
	return_day = [0 for i in range(no_boys)]
	for b in books:
		if return_day[i - 1] == 0:
			ans = 1
			if b == i:
				return_day[i - 1] = 1
				i = i + 1
				continue
			else:
				L = [i - 1]
				index = books[i - 1]
				while True:
					if books[index - 1] == i:
						ans += 1
						index = books[index - 1]
						L.append(books[index - 1] - 1)
						break
					else:
						L.append(books[index - 1] - 1)
						index = books[index - 1]
						ans += 1
				for k in L:
					return_day[k] = ans
				i += 1
		else:
			i = i + 1
	for i in return_day:
		print(i, end=' ')
	print(' ')


for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	ans = ''
	days = [0] * n
	for i in range(n):
		count = 0
		present = i
		if days[i] == 0:
			seen = []
			while True:
				present = p[present] - 1
				count += 1
				seen.append(present)
				if present == i:
					break
			for j in seen:
				days[j] = count
	print(*days)


import sys
input = sys.stdin.readline

def solve():
	q = int(input().rstrip())
	book = list(map(int, input().rstrip().split()))
	for i in range(q):
		day = 1
		tmp = book[i]
		while tmp != i + 1:
			day += 1
			tmp = book[tmp - 1]
		print(day, end=' ')
	print()
for _ in range(int(input())):
	solve()


import os
import sys
from io import BytesIO, IOBase
from math import sqrt

def solution(n, arr):
	arr.insert(0, 0)
	for i in range(1, n + 1):
		(res, p) = (1, arr[i])
		while p != i:
			p = arr[p]
			res += 1
		write(res, end='')
	write()

def main():
	for _ in range(r_int()):
		n = r_int()
		arr = r_array()
		solution(n, arr)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')

def write(*args, end='\n'):
	for x in args:
		sys.stdout.write(str(x) + ' ')
	sys.stdout.write(end)

def r_array():
	return [int(x) for x in input().split()]

def r_int():
	return int(input())

def w_array(arr):
	for x in arr:
		write(x, end=' ')
	write()
main()


def DFS(i, ans, d, visited):
	stack1 = [i]
	t = 0
	current = i
	stack2 = [i]
	while len(stack1):
		t = t + 1
		current = stack1.pop()
		if visited[current] == True:
			break
		visited[current] = True
		stack1.append(d[current])
		stack2.append(d[current])
	for i in stack2:
		ans[i] = t
q = int(input())
for i in range(q):
	n = int(input())
	d = {}
	l = list(map(int, input().split()))
	d = {i + 1: l[i] for i in range(n)}
	visited = {i + 1: False for i in range(n)}
	ans = {i + 1: 0 for i in range(n)}
	for i in range(1, n + 1):
		if visited[i] == False:
			DFS(i, ans, d, visited)
	for i in ans:
		print(ans[i] - 1, end=' ')
	print()


n = int(input())
for x in range(n):
	k = int(input())
	l = list(map(int, input().split()))
	l = [x - 1 for x in l]
	d = [-1] * k
	for i in range(k):
		if d[i] != -1:
			continue
		r = 1
		j = l[i]
		dd = []
		while True:
			dd.append(j)
			if i == j:
				for y in dd:
					d[y] = r
				break
			j = l[j]
			r += 1
	print(*d)


def make_smaller(num):
	return num - 1

def make_bigger(num):
	return num + 1

def B1():
	answer = ''
	for query in range(int(input())):
		am_of_kids = int(input())
		p = list(map(make_smaller, map(int, input().split())))
		answers = []
		for i in range(am_of_kids):
			answers.append(-1)
		i = 0
		while -1 in answers:
			if answers[i] == -1:
				used_kids = set([i])
				start_kid = i
				now_kid = p[start_kid]
				circle_len = 1
				while start_kid != now_kid:
					used_kids.add(now_kid)
					now_kid = p[now_kid]
					circle_len += 1
				for kid in used_kids:
					answers[kid] = circle_len
			i += 1
		answer += ' '.join(map(str, answers)) + '\n'
	print(answer)
B1()


t = int(input())

class DSU:

	def __init__(self, n):
		self.parent = [0] * n
		for i in range(n):
			self.parent[i] = i
		self.size = n
		self.final = [0] * n

	def find_set(self, x):
		if self.parent[x] == x:
			return x
		self.parent[x] = self.find_set(self.parent[x])
		return self.parent[x]

	def union_set(self, a, b):
		a = self.find_set(a)
		b = self.find_set(b)
		if a != b:
			self.parent[a] = b

	def find_parent_all(self):
		for i in range(self.size):
			self.parent[i] = self.find_set(i)
			self.final[self.parent[i]] += 1
		for i in range(self.size):
			print(self.final[self.parent[i]], end=' ')
		print('')
while t:
	t -= 1
	n = int(input())
	v = list(map(int, input().strip().split()))[:n]
	data = DSU(n)
	for (i, val) in enumerate(v):
		data.union_set(i, val - 1)
	data.find_parent_all()


import sys
input = sys.stdin.readline
n = int(input())
for _ in range(n):
	m = int(input())
	x = list(map(int, input().split()))
	x = [i - 1 for i in x]
	boo = [-1 for i in range(m)]
	setsizes = [0 for i in range(m)]
	setcount = 0
	for a in range(m):
		if boo[a] == -1:
			boo[a] = setcount
			cur = x[a]
			setsizes[setcount] += 1
			while cur != a:
				boo[cur] = setcount
				setsizes[setcount] += 1
				cur = x[cur]
			setcount += 1
	outs = []
	for i in range(m):
		outs.append(str(setsizes[boo[i]]))
	print(' '.join(outs))


from sys import stdin
import math
from collections import defaultdict
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	p = list(map(lambda x: int(x) - 1, stdin.readline().rstrip().split()))
	count = [0] * n
	for i in range(n):
		x = i
		while p[x] != i:
			count[i] += 1
			x = p[x]
		count[i] += 1
	print(*count)


for u in range(int(input())):
	n = int(input())
	l = [0] + list(map(int, input().split()))
	d = []
	for i in range(1, n + 1):
		x = i
		c = 1
		while x != l[i]:
			c = c + 1
			i = l[i]
		d.append(c)
	print(*d)


t = int(input())
b = []
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b.append(a)
for i in b:
	c = []
	for j in range(len(i)):
		t = i[j]
		p = 0
		while t != j + 1:
			t = i[t - 1]
			p += 1
		c.append(p + 1)
	for k in c:
		print(k, end=' ')
	print()


class Stack:

	def __init__(self, size):
		self.Top = -1
		self.Data = None
		self.arr = [None] * size
		self.Size = size

	def Empty(self):
		if self.Top == -1:
			return True
		else:
			return False

	def Push(self, data):
		if self.Top == self.Size - 1:
			print('Overflow')
		else:
			self.Top = self.Top + 1
			self.arr[self.Top] = data

	def Pop(self):
		if not self.Empty():
			x = self.arr[self.Top]
			self.Top = self.Top - 1
			return x
for _ in range(int(input())):
	n = int(input())
	ans = [None] * n
	S = Stack(n)
	a = list(map(int, input().split()))
	for i in range(n):
		if ans[i] is None:
			FstPos = i
			fstjump = 1
			goto = -1
			cnt = 0
			while goto != FstPos:
				if fstjump == 1:
					goto = a[i] - 1
					fstjump = 0
					S.Push(goto)
				else:
					goto = a[goto] - 1
					S.Push(goto)
				cnt += 1
			while not S.Empty():
				ans[S.Pop()] = cnt
	for i in ans:
		print(i, end=' ')
	print()


def poisk(q, l):
	global ans, b
	if ans[q] > 0:
		return
	if ans[q] == 0:
		ans[q] = -1
		ans[q] = poisk(p[q] - 1, l + 1)
		return ans[q]
	if ans[q] == -1:
		ans[q] = l + 1
		return l + 1
R = lambda : list(map(int, input().split()))
(q,) = R()
for i in range(q):
	(n,) = R()
	ans = n * [0]
	p = R()
	for i2 in range(n):
		poisk(i2, -1)
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	cs = list(map(int, input().split()))
	pb = cs[0]
	d = 1
	ans = []
	for f in range(n):
		pnt = f
		cnt = 1
		while cs[pnt] != f + 1:
			cnt += 1
			pnt = cs[pnt] - 1
		ans.append(str(cnt))
	print(' '.join(ans))


def main():

	def find(x):
		if par[x] < 0:
			return x
		else:
			par[x] = find(par[x])
			return par[x]

	def unite(x, y):
		x = find(x)
		y = find(y)
		if x == y:
			return False
		else:
			if par[x] > par[y]:
				(x, y) = (y, x)
			par[x] += par[y]
			par[y] = x
			return True

	def same(x, y):
		return find(x) == find(y)

	def size(x):
		return -par[find(x)]
	q = int(input())
	for _ in [0] * q:
		n = int(input())
		p = list(map(int, input().split()))
		par = [-1] * n
		for (i, e) in enumerate(p):
			unite(i, e - 1)
		for i in range(n):
			print(size(i), end=' ')
		print('')
main()


t = int(input())
from collections import defaultdict
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().strip().split()))[:n]
	for i in range(n):
		arr[i] -= 1
	used = [False] * n
	ans = [0] * n
	for i in range(n):
		if used[i] == False:
			cur = []
			while used[i] == False:
				cur.append(i)
				used[i] = True
				i = arr[i]
			for ele in cur:
				ans[ele] = len(cur)
	for i in range(n):
		print(ans[i], end=' ')
	print()


import sys
input = sys.stdin.buffer.readline
N = int(input())
for _ in range(N):
	n = int(input())
	a = list(map(int, input().split()))
	res = []
	for i in range(n):
		p = a[i]
		d = 1
		while p != i + 1:
			p = a[p - 1]
			d += 1
		res.append(d)
	print(*res)


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	a = list(map(int, input().split()))
	for i in range(n):
		a[i] -= 1
	p = [i for i in range(n)]
	sz = [1 for i in range(n)]

	def find(i):
		if i != p[i]:
			p[i] = find(p[i])
		return p[i]

	def union(i, j):
		i = find(i)
		j = find(j)
		if sz[i] > sz[j]:
			p[j] = i
			sz[i] += sz[j]
		else:
			p[i] = j
			sz[j] += sz[i]
	for i in range(n):
		if find(i) != find(a[i]):
			union(i, a[i])
	for i in range(n):
		print(sz[find(i)], end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	for i in range(n):
		a[i] -= 1
	ans = [0] * n
	used = [False] * n
	for i in range(n):
		if used[i] is False:
			cur = []
			while used[i] is False:
				cur.append(i)
				used[i] = True
				i = a[i]
			for ele in cur:
				ans[ele] = len(cur)
	for num in ans:
		print(num, end=' ')
	print()


tests = int(input())
for te in range(tests):
	n = int(input())
	arr = list(map(int, input().split()))
	ans = [0 for i in range(n)]
	for i in range(n):
		if ans[i] == 0:
			index = i
			count = 0
			index_arr = []
			index_arr.append(i)
			for j in range(n):
				index = arr[index] - 1
				index_arr.append(index)
				count += 1
				if i == index:
					break
			for j in range(len(index_arr)):
				ans[index_arr[j]] = count
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	x = []
	for i in a:
		q = i
		p = 1
		while 1:
			if a[i - 1] == q:
				x.append(p)
				break
			i = a[i - 1]
			p += 1
	print(*x)


for _ in range(int(input())):
	n = int(input())
	lis = [8] + list(map(int, input().split()))
	c = 1
	ans = [0] * (n + 1)
	temp = []
	for i in range(1, n + 1):
		if ans[i] != 0:
			continue
		if lis[i] == i:
			ans[i] = 1
			continue
		j = lis[i]
		temp.append(j)
		while j != i:
			j = lis[j]
			temp.append(j)
			c += 1
		for k in temp:
			ans[k] = c
		temp = []
		c = 1
	print(*ans[1:])


def dfs(u, scc, p, par, sz):
	par[u] = scc
	sz[scc] += 1
	if par[p[u]] == -1:
		dfs(p[u], scc, p, par, sz)
for i in range(int(input())):
	n = int(input())
	p = list(map(lambda x: int(x) - 1, input().split()))
	par = [-1] * n
	sz = [0] * n
	for i in range(n):
		if par[i] == -1:
			dfs(i, i, p, par, sz)
	for i in range(n):
		print(sz[par[i]], end=' ')
	print('')


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	s = input()
	v = []
	v = s.split()
	for i in range(0, len(v)):
		v[i] = int(v[i])
	v = [0] + v[:]
	viz = [0] * (n + 2)
	val = [0] * (n + 2)
	sol = []
	pwp = 0
	for i in range(1, n + 1):
		if viz[i] != 0:
			sol.append(val[viz[i]])
			continue
		if v[i] == i:
			sol.append(1)
			continue
		pwp += 1
		act = i
		st = i
		nr = 0
		ok = 0
		while act != st or ok == 0:
			ok = 1
			viz[act] = pwp
			nr += 1
			act = v[act]
		val[pwp] = nr
		sol.append(nr)
	print(*sol)


def solve():
	n = int(input())
	p = list(map(int, input().split()))
	pp = [i for i in range(1, n + 1)]
	day = 0
	result = [0] * n
	while 0 in result:
		day += 1
		ppp = pp.copy()
		for i in range(n):
			rp = p[i] - 1
			pp[rp] = ppp[i]
			if pp[rp] == rp + 1 and result[rp] == 0:
				result[rp] = day
	print(*result)
for _ in range(int(input())):
	solve()


q = int(input())
for _ in range(q):
	n = int(input())
	items = list(map(int, input().split()))
	days = [-1 for i in range(n)]
	unfound = set([i for i in range(n)])
	while len(unfound) > 0:
		i = unfound.pop()
		if days[i] == -1:
			seq = [i]
			start = i
			curr = i
			k = 0
			while k != 2:
				curr = items[curr] - 1
				seq.append(curr)
				if curr == start:
					k += 1
			indexes = dict()
			for (j, item) in enumerate(seq):
				if item not in indexes:
					indexes[item] = j
				elif days[item] == -1:
					if i != item:
						unfound.remove(item)
					days[item] = j - indexes[item]
	print(' '.join(map(str, days)))


def position():
	n = int(input())
	m = list(map(int, input().split()))
	for i in range(n):
		pos = m[i]
		a = 1
		while pos != i + 1:
			a += 1
			pos = m[pos - 1]
		else:
			print(a, end=' ')
			continue
q = int(input())
for _ in range(q):
	position()


q = int(input())

def find_cycle(now, p):
	out = set([])
	while p[now] not in out:
		out.add(p[now])
		now = p[now]
	return out
for i in range(q):
	n = int(input())
	p = [int(x) - 1 for x in input().split()]
	out = n * [None]
	not_seen = set(range(0, n))
	group = 0
	while len(not_seen) > 0:
		now = not_seen.pop()
		cycle = find_cycle(now, p)
		lc = len(cycle)
		for k in cycle:
			out[k] = lc
			if k != now:
				not_seen.remove(k)
	print(*out)


t = int(input())
for _ in range(t):
	whoNext = {}
	exin_n_students = input()
	exin_order = input()
	exin_order = list(exin_order.split(' '))
	x = 1
	totalResult = []
	for i in range(int(exin_n_students)):
		lookingFor = str(i + 1)
		currentDude = str(i + 1)
		nex = exin_order[i]
		result = 1
		while lookingFor != nex:
			currentDude = nex
			nex = exin_order[int(currentDude) - 1]
			result = result + 1
		totalResult.append(result)
	for i in totalResult:
		print(i, end=' ')
	print('')


t = int(input())
for _ in range(t):
	n = int(input())
	a = [0] + list(map(int, input().split()))
	d = dict()
	for i in range(1, n + 1):
		d[i] = 0
	for i in range(1, n + 1):
		if d[i]:
			continue
		idx = i
		v = []
		v.append(idx)
		num = 1
		while a[idx] != i:
			num += 1
			idx = a[idx]
			v.append(idx)
		for i in range(len(v)):
			d[v[i]] = num
	for i in range(1, n + 1):
		print(d[i], end=' ')
	if _ != t - 1:
		print()


q = int(input())
for _ in range(q):
	n = int(input())
	arr = [0] + [int(x) for x in input().split()]
	ans = [0] * n
	for i in range(1, n + 1):
		res = 0
		j = i
		while arr[j] != i:
			j = arr[j]
			res += 1
		ans[i - 1] = res + 1
	print(*ans)


import sys

def input():
	return sys.stdin.readline()

class DSU(object):

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.rank = [1] * n
		self.cycle = False

	def find(self, key):
		if self.parent[key] != key:
			self.parent[key] = self.find(self.parent[key])
		return self.parent[key]

	def union(self, a, b):
		(s1, s2) = (self.find(a), self.find(b))
		if s1 != s2:
			if self.rank[s1] < self.rank[s2]:
				self.parent[s1] = s2
				self.rank[s2] += self.rank[s1]
			else:
				self.parent[s2] = s1
				self.rank[s1] += self.rank[s2]
		else:
			self.cycle = True

	def has_cycle(self):
		return self.cycle

	def show_parent(self):
		return self.parent

	def show_rank(self):
		return self.rank
test_case = int(input())
for _ in range(test_case):
	n = int(input())
	a = list(map(int, input().split()))
	d = DSU(n + 1)
	for i in range(n):
		d.union(i + 1, a[i])
	for i in range(n):
		print(d.rank[d.find(a[i])], end=' ')
	print()


from collections import deque

def solve(n, arr):
	res = deque()
	for i in range(n):
		ans = 1
		cur = arr[i] - 1
		while i != cur:
			ans += 1
			cur = arr[cur] - 1
		res.append(ans)
	return res
q = int(input())
for qq in range(q):
	n = int(input())
	arr = list(map(int, input().split()))
	print(*solve(n, arr))


import sys
q = int(input())
for case in range(q):
	n = int(input())
	p = list(map(int, input().split()))
	ans = [0] * n
	for i in range(n):
		if ans[i] == 0:
			cycle = []
			(d, l) = (p[i] - 1, 1)
			cycle.append(i)
			while d != i:
				cycle.append(d)
				d = p[d] - 1
				l += 1
			for x in cycle:
				ans[x] = l
	for a in ans:
		print(a, end=' ')
	print('')


import sys
input = sys.stdin.readline
q = int(input())
for _ in range(q):
	n = int(input())
	arr = list(map(int, input().split()))
	ans = [0] * (n + 1)
	for i in range(n):
		if arr[i] == i + 1:
			ans[i + 1] = 1
		elif ans[i + 1] == 0:
			temp = list()
			temp.append(i + 1)
			nex = arr[i]
			while nex != i + 1:
				temp.append(nex)
				nex = arr[nex - 1]
			for j in range(len(temp)):
				ans[temp[j]] = len(temp)
	for i in range(1, len(ans)):
		print(ans[i], end=' ')
	print()


def make_set(arr, d):
	for i in range(len(arr)):
		d[i + 1] = arr[i]

def find_set(d, i, o):
	if d[i] == o:
		return 1
	return find_set(d, d[i], o) + 1
T = int(input())
for t in range(T):
	n = int(input())
	arr = list(map(int, input().split()))
	d = {}
	make_set(arr, d)
	for i in range(len(arr)):
		print(find_set(d, i + 1, i + 1), end=' ')
	print()


def task_2(childrens, values):
	answer = [0] * childrens
	first_row = list(range(1, childrens + 1))
	for i in range(1, childrens + 1):
		cycle = 1
		if first_row[i - 1] == values[i - 1]:
			pass
		else:
			index = values[i - 1]
			while index != i:
				index = values[index - 1]
				cycle += 1
		answer[i - 1] = cycle
	print(*answer)
q = int(input())
for q in range(q):
	(childrens,) = map(int, input().rstrip().split())
	values = list(map(int, input().rstrip().split()))
	task_2(childrens, values)


q = int(input())
for _ in range(q):
	n = int(input())
	a = [0] + list(map(int, input().split()))
	for i in range(1, n + 1):
		days = 1
		next_ = a[i]
		while next_ != i:
			next_ = a[next_]
			days += 1
		print(days, end=' ')
	print()


q = int(input())
for _ in range(q):
	n = int(input())
	Q = list(map(int, input().split()))
	res = [1] * n
	for i in range(n):
		if res[i] == 1:
			t = Q[i]
			tl = [t]
			while t != i + 1:
				t = Q[t - 1]
				tl.append(t)
				res[i] += 1
			for k in tl:
				res[k - 1] = res[i]
	print(*res)


for i in range(int(input())):
	n = int(input())
	p = [int(i) - 1 for i in input().split()]
	d = []
	e = set()
	for i in range(n):
		if p[i] in e:
			continue
		e.add(p[i])
		r = [p[i]]
		a = p[i]
		while a != i:
			e.add(p[a])
			r.append(p[a])
			a = p[a]
		d.append(r)
	t = [0 for i in range(n)]
	for i in d:
		b = len(i)
		for j in i:
			t[j] = b
	print(*t)


t = int(input())
s = []
for fnj in range(0, t):
	n = int(input())
	x = input()
	p = x.split()
	q = []
	for i in range(0, n):
		y = i
		g = 1
		y = int(p[y]) - 1
		while y != i:
			g += 1
			y = int(p[y]) - 1
		q.append(g)
	s.append(q)
for i in s:
	for j in i:
		print(j, end=' ')
	print()


import sys
t = int(sys.stdin.readline())
for _ in range(t):
	n = int(sys.stdin.readline())
	arr = [0] + list(map(int, sys.stdin.readline().split()))
	result = []
	table = [0] * (n + 1)
	for i in range(1, n + 1):
		day = 1
		idx = arr[i]
		if table[idx] != 0:
			pass
		elif idx == i:
			table[i] = day
		else:
			temp = []
			while idx != i:
				day += 1
				temp.append(idx)
				idx = arr[idx]
			temp.append(idx)
			for j in temp:
				table[j] = day
	result = ' '.join(list(map(str, table[1:])))
	print(result)


T = int(input())
for i in range(T):
	n = int(input())
	A = list(map(int, input().strip().split()))
	B = [-1 for j in range(n)]
	for j in range(n):
		if B[j] == -1:
			a = set([A[j]])
			b = A[A[j] - 1]
			count = 1
			while b != A[j]:
				a.add(b)
				b = A[b - 1]
				count = count + 1
			for k in a:
				B[k - 1] = str(count)
	print(' '.join(B))


for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	p = [x - 1 for x in p]
	for i in range(len(p)):
		ch = p[i]
		ans = 1
		while ch != i:
			ch = p[ch]
			ans += 1
		print(ans, end=' ')


t = int(input())
for _ in range(t):
	n = int(input())
	l = [0] + list(map(int, input().split()))
	b = [0] * (n + 1)
	for i in range(1, n + 1):
		ans = 1
		if b[i] != 0:
			continue
		c = list()
		(k, p) = (i, i)
		c.append(i)
		while l[p] != i:
			ans += 1
			c.append(p)
			p = l[p]
		for j in c:
			b[j] = ans
	print(*b[1:])


q = int(input())
for i in range(q):
	n = int(input())
	inp = input()
	inp_arr = inp.split(' ')
	inp_arr = [int(j) for j in inp_arr]
	out_arr = []
	for j in range(n):
		count = 1
		curr = inp_arr[j] - 1
		while curr != j:
			curr = inp_arr[curr] - 1
			count += 1
		out_arr.append(str(count))
	out = ' '.join(out_arr)
	print(out)


def dfs(edges, node, connected_cmpts, visited):
	cmpts = []
	stack = [node]
	while stack:
		curr = stack.pop()
		if curr not in visited:
			cmpts.append(curr)
			visited.add(curr)
			for kid in edges[curr]:
				stack.append(kid)
	connected_cmpts.append(cmpts)

def solve(arr, n):
	edges = {}
	for i in range(1, n + 1):
		edges[i] = []
	for i in range(n):
		edges[i + 1].append(arr[i])
	connected_cmpts = []
	visited = set()
	for i in range(1, n + 1):
		if i not in visited:
			dfs(edges, i, connected_cmpts, visited)
	ans = [0] * (n + 1)
	for i in connected_cmpts:
		for j in i:
			ans[j] = len(i)
	for i in range(1, n + 1):
		print(ans[i], end=' ')
	print()

def main():
	q = int(input())
	for i in range(q):
		n = int(input())
		arr = list(map(int, input().split()))
		solve(arr, n)
main()


def kek(a, b, s=0):
	s += 1
	if a == b:
		return s
	return kek(data[a - 1], b, s)
for q in range(int(input())):
	n = int(input())
	data = [int(i) for i in input().split()]
	visited = [0 for i in range(n)]
	for i in range(n):
		visited[i] = kek(data[i], i + 1)
	print(' '.join([str(i) for i in visited]))


Q = int(input())
for q in range(Q):
	N = int(input())
	P = list(map(int, input().split()))
	out = [False for i in range(N)]
	for p in range(N):
		if out[p] == False:
			o = 1
			use = [p]
			i = P[p]
			while i != p + 1:
				use.append(i - 1)
				i = P[i - 1]
				o += 1
			for u in use:
				out[u] = str(o)
	print(' '.join(out))


import math
from sys import stdin, stdout
import atexit
import io
import sys
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER

@atexit.register
def write():
	sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())

def pnt(x):
	stdout.write(str(x) + '\n')

def pnt(x, end=' '):
	stdout.write(str(x) + end)
inp = lambda : int(input())
sip = lambda : input()
mulip = lambda : map(int, input().split())
lst = lambda : list(map(int, stdin.readline().split()))
sarr = lambda : list(map(str, stdin.readline().split()))
slst = lambda : list(sip())
arr2d = lambda N: [[int(x) for x in input().split()] for i in range(N)]
for _ in range(inp()):
	n = inp()
	A = [0] + list(map(int, input().split()))
	res = [0] * (n + 1)
	for i in range(1, n + 1):
		j = A[i]
		cnt = 1
		while j != i:
			j = A[j]
			cnt += 1
		res[i] = cnt
	for i in range(1, n + 1):
		print(res[i], end=' ')
	print()


class Glass:

	def __init__(self, a):
		self.gd = {}
		self.a = a
		for i in range(len(self.a)):
			self.gd[i] = [self.a[i] - 1]

	def edges(self, fromNode, toNode):
		self.gd[self.a[fromNode - 1]].append(self.a[toNode - 1])

	def cycle_len(self, key, unq):
		if self.a[key] in v:
			cyl[key] = unq
			v.pop(v.index(self.a[key]))
			self.cycle_len(self.gd[key][0], unq)
		return
q = int(input())
ans = []
for k in range(q):
	ans.append([])
for t in range(q):
	n = int(input())
	a = [int(k) for k in input().split()]
	g = Glass(a)
	v = a.copy()
	cyl = [0] * n
	unq = 0
	while v:
		i = v[0]
		g.cycle_len(a.index(i), unq)
		unq += 1
	for i in range(n):
		s = cyl.count(cyl[i])
		ans[t].append(s)
for i in ans:
	for j in i:
		print(j, end=' ')
	print(sep=' ')


q = int(input())
for i in range(q):
	n = int(input())
	p = list(map(int, input().split(' ')))
	for j in range(n):
		p[j] -= 1
	perms = [-1] * (n + 1)
	for j in range(n):
		temp = j
		count = 1
		while j != p[temp]:
			count += 1
			temp = p[temp]
		perms[j] = count
	for j in range(n):
		print(perms[j], end=' ')


import sys
input = sys.stdin.readline
q = int(input())
for _ in range(q):
	n = int(input())
	p = list(map(int, input().split()))
	for i in range(n):
		p[i] -= 1
	flag = [-1] * n
	ans = [-1] * n
	for i in range(n):
		cur = i
		if flag[cur] == 1:
			continue
		flag[cur] = 1
		l = [cur]
		while True:
			if flag[p[cur]] == 1:
				break
			if flag[p[cur]] == -1:
				flag[p[cur]] = 1
			cur = p[cur]
			l.append(cur)
		for li in l:
			ans[li] = len(l)
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	ans = []
	for i in range(n):
		c = 1
		x = l[i]
		while x != i + 1:
			x = l[x - 1]
			c += 1
		ans.append(c)
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	p = list(map(lambda i: int(i) - 1, input().split()))
	b = [0] * n
	for i in range(n):
		if b[i]:
			continue
		j = p[i]
		y = [i]
		c = 1
		while j != i:
			y.append(j)
			j = p[j]
			c += 1
		for i in y:
			b[i] = c
	print(*b)


for _ in range(int(input())):
	n = int(input())
	l = [0] + [int(x) for x in input().split()]
	ans = [0] * (n + 1)
	for i in range(1, n + 1):
		if i == l[i]:
			ans[i] = 1
		else:
			j = i
			while True:
				ans[i] += 1
				if i == l[j]:
					break
				j = l[j]
	print(*ans[1:])


ii = lambda : int(input())
kk = lambda : map(int, input().split())
ll = lambda : list(kk())
for _ in range(ii()):
	(n, ls) = (ii(), list(map(lambda x: int(x) - 1, input().split())))
	vis = [0] * n
	for i in range(n):
		if not vis[i]:
			(i2, l) = (ls[i], 1)
			while i2 != i:
				i2 = ls[i2]
				l += 1
			(vis[i], i2) = (l, ls[i])
			while i2 != i:
				vis[i2] = l
				i2 = ls[i2]
	print(*vis)


import sys
input = sys.stdin.readline
from collections import deque

def search(arr, node):
	nodes = set()
	turns = 0
	origin = node
	cur = arr[node]
	nodes.add(cur)
	while cur != origin:
		cur = arr[cur]
		turns += 1
		nodes.add(cur)
	return (turns + 1, nodes)

def calc(n, arr):
	visited = [0] * n
	res = [0] * n
	for node in range(n):
		if visited[node]:
			continue
		(length, nodes) = search(arr, node)
		for pro_node in nodes:
			res[pro_node] = length
			visited[pro_node] = 1
	return res
q = int(input())
for _ in range(q):
	n = int(input())
	arr = list(map(lambda x: int(x) - 1, input().split()))
	print(*calc(n, arr))


from sys import stdin, stdout
input = stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	l = [0] + list(map(int, input().split()))
	b = [0] * (n + 1)
	for i in range(1, n + 1):
		ans = 1
		if b[i] != 0:
			continue
		c = list()
		(k, p) = (i, i)
		c.append(i)
		while l[p] != i:
			ans += 1
			c.append(p)
			p = l[p]
		for j in c:
			b[j] = ans
	print(*b[1:])


t = int(input())
for z in range(t):
	n = int(input())
	a = list(map(int, input().strip().split()))
	op = [0] * n
	for i in range(n):
		c = 1
		x = a[i] - 1
		while x != i:
			x = a[x] - 1
			c += 1
		op[i] = c
	print(' '.join(list(map(str, op))))


for _ in range(int(input())):
	(n, p) = (int(input()), list(map(int, input().split())))
	(total, i) = (0, 0)
	res = [0] * n
	while i < n:
		if res[i] == 0:
			(j, cnt) = (i, 1)
			while p[j] - 1 != i:
				cnt += 1
				j = p[j] - 1
			j = i
			for _ in range(cnt):
				res[j] = cnt
				j = p[j] - 1
			total += cnt
		i += 1
	print(*res)


import math, sys
from collections import defaultdict, Counter, deque
INF = float('inf')
MOD = 1000000007

def gcd(a, b):
	while b:
		(a, b) = (b, a % b)
	return a

def isPrime(n):
	if n <= 1:
		return False
	i = 2
	while i ** 2 <= n:
		if n % i == 0:
			return False
		i += 1
	return True

def primeFactors(n):
	factors = []
	i = 2
	while i ** 2 <= n:
		while n % i == 0:
			factors.append(i)
			n //= i
		i += 1
	if n > 1:
		factors.append(n)
	return factors

def vars():
	return map(int, input().split())

def array():
	return list(map(int, input().split()))
ans = 0

def dfs(visited, node, digits, tree):
	if not visited[node]:
		visited[node] = True
		digits += str(node)
		leafNode = True
		for child in tree[node]:
			leafNode = False
			dfs(visited, child, digits, tree)
		if leafNode:
			global ans
			ans += int(digits)

def main():
	n = int(input())
	arr = array()
	ans = []
	for i in range(n):
		pos = arr[i] - 1
		cnt = 1
		while i != pos:
			pos = arr[pos] - 1
			cnt += 1
		ans.append(cnt)
	print(*ans)
t = int(input())
for _ in range(t):
	main()


q = int(input())

def find_cycle(now):
	out = set([])
	while p[now] not in out:
		out.add(p[now])
		cycle_id[now] = group
		now = p[now]
	return out
for i in range(q):
	n = int(input())
	p = [int(x) - 1 for x in input().split()]
	out = n * [None]
	cycle_id = n * [-1]
	group = 0
	for j in range(0, n):
		if cycle_id[j] > -1:
			continue
		cycle = find_cycle(j)
		group = group + 1
		lc = len(cycle)
		for k in cycle:
			out[k] = lc
	print(*out)


import math
from sys import stdin, stdout

def pnt(x):
	stdout.write(str(x) + '\n')

def pnt(x, end=' '):
	stdout.write(str(x) + end)
inp = lambda : int(stdin.readline())
sip = lambda : input()
mulip = lambda : map(int, input().split())
lst = lambda : list(map(int, stdin.readline().split()))
sarr = lambda : list(map(str, stdin.readline().split()))
slst = lambda : list(sip())
arr2d = lambda N: [[int(x) for x in input().split()] for i in range(N)]
for _ in range(inp()):
	n = inp()
	A = [0]
	_ = [A.append(int(x)) for x in input().split()]
	res = [0] * (n + 1)
	for i in range(1, n + 1):
		j = A[i]
		cnt = 1
		while j != i:
			j = A[j]
			cnt += 1
		res[i] = cnt
	for i in range(1, n + 1):
		print(res[i], end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	a = [int(i) - 1 for i in input().split()]
	ans = [None] * len(a)
	vis = set()
	for i in range(len(a)):
		if i not in vis:
			day = i
			cnt = 1
			tmp = a[i]
			tmp_vis = set()
			vis.add(tmp)
			tmp_vis.add(tmp)
			while day != tmp:
				tmp = a[tmp]
				vis.add(tmp)
				tmp_vis.add(tmp)
				cnt += 1
			for el in tmp_vis:
				ans[el] = cnt
	print(*ans)


for q in range(int(input())):
	n = int(input())
	ar = list(map(int, input().split(' ')))
	ar = [0] + ar
	for i in range(1, n + 1):
		c = ar[i]
		t = 1
		while c != i:
			c = ar[c]
			t += 1
		print(t, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	a = [int(i) - 1 for i in input().split()]
	used = [False] * n
	ans = [0] * n
	for j in range(n):
		if not used[j]:
			cur = []
			while not used[j]:
				cur.append(j)
				used[j] = True
				j = a[j]
			for el in cur:
				ans[el] = len(cur)
	for j in range(n):
		print(ans[j], end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	ans = [0] * n
	used = set()
	for i in range(n):
		if i not in used:
			curr = set()
			curr.add(i)
			x = l[i] - 1
			cnt = 1
			while True:
				if x == i:
					break
				used.add(x)
				curr.add(x)
				x = l[x] - 1
				cnt += 1
			while len(curr) != 0:
				el = curr.pop()
				ans[el] = cnt
	for i in range(n):
		print(ans[i], end=' ')
	print()


import sys
input = sys.stdin.readline
q = int(input())

def find(x):
	while Group[x] != x:
		x = Group[x]
	return x

def Union(x, y):
	if find(x) != find(y):
		Group[find(y)] = Group[find(x)] = min(find(y), find(x))
for testcases in range(q):
	n = int(input())
	P = list(map(int, input().split()))
	Group = [i for i in range(n)]
	for i in range(n):
		Union(i, P[i] - 1)
	G = [find(i) for i in range(n)]
	count = [0] * n
	for g in G:
		count[g] += 1
	for i in range(n):
		print(count[G[i]], end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	p = ['0' for _ in range(n)]
	l = [int(x) - 1 for x in input().split()]
	for num in range(n):
		t = []
		sum = 0
		x = l[num]
		if p[num] == '0':
			while x != num:
				t.append(x)
				x = l[x]
				sum += 1
			t.append(num)
			for nn in t:
				p[l.index(nn)] = sum
	for nnn in p:
		print(nnn + 1, end=' ')
	print('')


n = int(input())
for i in range(n):
	m = int(input())
	mass = [int(x) for x in input().split()]
	arr = [0] * m
	q = [0] * (m + 3)
	for j in range(m):
		if arr[j] == 0:
			ch = mass[j] - 1
			answer = 1
			if mass[j] - 1 != j:
				q[1] = mass[j] - 1
			q[0] = j
			while ch != j:
				ch = mass[ch] - 1
				answer += 1
				q[answer] = ch
			for l in range(answer):
				arr[q[l]] = answer
	print(*arr)


import sys
import math
import heapq
import bisect
from collections import Counter
from collections import defaultdict
from io import BytesIO, IOBase
import string

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None
		self.BUFSIZE = 8192

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def get_int():
	return int(input())

def get_ints():
	return list(map(int, input().split(' ')))

def get_int_grid(n):
	return [get_ints() for _ in range(n)]

def get_str():
	return input().split(' ')

def yes_no(b):
	if b:
		return 'YES'
	else:
		return 'NO'

def binary_search(good, left, right, delta=1, right_true=False):
	limits = [left, right]
	while limits[1] - limits[0] > delta:
		if delta == 1:
			mid = sum(limits) // 2
		else:
			mid = sum(limits) / 2
		if good(mid):
			limits[int(right_true)] = mid
		else:
			limits[int(~right_true)] = mid
	if good(limits[int(right_true)]):
		return limits[int(right_true)]
	else:
		return False

def prefix_sums(a, drop_zero=False):
	p = [0]
	for x in a:
		p.append(p[-1] + x)
	if drop_zero:
		return p[1:]
	else:
		return p

def prefix_mins(a, drop_zero=False):
	p = [float('inf')]
	for x in a:
		p.append(min(p[-1], x))
	if drop_zero:
		return p[1:]
	else:
		return p

class DSU:

	def __init__(self, nodes):
		self.p = [i for i in range(nodes)]
		self.r = [0 for i in range(nodes)]
		self.s = [1 for i in range(nodes)]

	def get(self, u):
		if u != self.p[u]:
			self.p[u] = self.get(self.p[u])
		return self.p[u]

	def union(self, u, v):
		u = self.get(u)
		v = self.get(v)
		if u != v:
			if self.r[u] > self.r[v]:
				(u, v) = (v, u)
			self.p[u] = v
			if self.r[u] == self.r[v]:
				self.r[v] += 1
			self.s[v] += self.s[u]

	def get_size(self, u):
		u = self.get(u)
		return self.s[u]

def solve_b():
	n = get_int()
	p = get_ints()
	dsu = DSU(n)
	for (i, x) in enumerate(p):
		dsu.union(i, x - 1)
	return [dsu.get_size(i) for i in range(n)]
t = get_int()
for _ in range(t):
	print(*solve_b())


q = int(input())
for qq in range(q):
	n = int(input())
	arr = list(map(int, input().split()))
	ans = [0] * n
	for i in range(n):
		if ans[i] != 0:
			continue
		c = arr[i] - 1
		temp = [i]
		res = 1
		while arr[c] != arr[i]:
			temp.append(c)
			c = arr[c] - 1
			res += 1
		for i in temp:
			ans[i] = res
	print(*ans)


from collections import defaultdict as dd
t = int(input())
while t:
	n = int(input())
	res = [0] * n
	l = list(map(int, input().split()))
	d = dd(int)
	for i in range(1, n + 1):
		d[i] = l[i - 1]
	for i in range(1, n + 1):
		aa = d[i]
		a = d[i]
		di = 0
		li = [a]
		if res[i - 1] == 0:
			while 1:
				a = l[a - 1]
				di += 1
				li.append(a)
				if a == aa:
					break
			for i in li:
				res[i - 1] = di
	print(*res)
	t -= 1


t = int(input())
while t:
	n = int(input())
	l = list(map(int, input().split()))
	for i in l:
		aa = i
		a = i
		d = 0
		while 1:
			a = l[a - 1]
			d += 1
			if a == aa:
				break
		print(d, end=' ')
	print()
	t -= 1


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	ans = []
	i = 1
	for t in range(n):
		j = t
		an1 = 1
		if l[j] == i:
			ans.append(an1)
		else:
			while l[j] != i:
				j = l[j] - 1
				an1 += 1
			ans.append(an1)
		i += 1
	print(*ans, sep=' ')


t = int(input())
sol = []
while t:
	t -= 1
	n = int(input())
	a = [int(i) for i in input().split()]
	if n == 1:
		sol.append(a)
	else:
		d = {i: True for i in range(n)}
		ciclii = []
		actual = []
		for i in range(n):
			j = i
			while a[j] - 1 != j and d[j]:
				d[j] = False
				actual.append(a[j] - 1)
				j = a[j] - 1
			if len(actual):
				ciclii.append(actual)
				actual = []
		for i in ciclii:
			h = len(i)
			for j in i:
				a[j] = h
		for i in d.keys():
			if d[i] == True:
				a[i] = 1
		sol.append(a)
for i in sol:
	print(*i)


def solve(arr, size):
	days = []
	for i in range(1, size + 1):
		pos = i
		count = 1
		while arr[i - 1] != pos:
			count += 1
			i = arr[i - 1]
		days.append(str(count))
	print(' '.join(days))
for _ in range(int(input())):
	size = int(input())
	arr = list(map(int, input().split()))
	solve(arr, size)


from sys import stdin
input = lambda : stdin.readline().rstrip('\r\n')
input_a = lambda fun: map(fun, stdin.readline().split())

def read():
	n = int(input())
	p = list(map(lambda x: x - 1, input_a(int)))
	return (n, p)

def solve(n, p: list):
	cycles: list = [None] * n
	sizes = {}
	c = 0
	for i in range(n):
		if cycles[i] is None:
			c += 1
			sizes[c] = 1
			cycles[i] = c
			j = p[i]
			while j != i:
				sizes[c] += 1
				cycles[j] = c
				j = p[j]
	return [sizes[x] for x in cycles]
for t in range(int(input())):
	result = solve(*read())
	print(*result)


def problem(l):
	for i in range(len(l)):
		c = 1
		melei = l[i]
		j = l[melei - 1]
		while melei != j:
			c += 1
			j = l[j - 1]
		print(c, end=' ')
	print('\n')
q = int(input())
for i in range(q):
	n = int(input())
	str = input()
	l = str.split()
	l = [int(item) for item in l]
	problem(l)


q = int(input())

def ruturnn(books, st):
	s = books[st]
	for i in range(len(books)):
		if s == st + 1:
			print(i + 1, end='  ')
			break
		else:
			s = books[s - 1]
for i in range(q):
	n = int(input())
	Books = list((int(i) for i in input().split()))
	for i in range(n):
		ruturnn(Books, i)


t = int(input())
for _ in range(t):
	children = []
	used_noms = []
	circle = []
	n = int(input())
	counters = [0] * n
	children = list(map(int, input().split()))
	for i in range(n):
		if i not in used_noms:
			counter = 1
			k = i
			while children[k] != i + 1:
				used_noms.append(k)
				k = children[k] - 1
				counter += 1
			k = i
			while children[k] != i + 1:
				k = children[k] - 1
				counters[k] = counter
			counters[i] = counter
	print(*counters)


import sys
from collections import defaultdict
input = sys.stdin.readline

def dfs(g, s, n):
	vis = [0] * (n + 1)
	st = [s]
	while st:
		x = st[-1]
		for i in g[x]:
			if i == s:
				return st
			if vis[i] == 0:
				vis[i] = 1
				st.append(i)
				break
		else:
			st.pop()
for _ in range(int(input())):
	n = int(input())
	lis = list(map(int, input().split()))
	g = defaultdict(list)
	for i in range(n):
		g[i + 1].append(lis[i])
	res = [0] * (n + 1)
	for i in range(1, n + 1):
		if res[i] == 0:
			v = dfs(g, i, n)
			for j in v:
				res[j] = len(v)
	print(*res[1:])


from math import *
t = int(input())
for y in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	for i in range(n):
		j = i
		ct = 0
		while i != a[j] - 1:
			j = a[j] - 1
			ct += 1
		print(ct + 1, end=' ')
	print()


t = int(input())
for _ in range(t):
	skaits = int(input())
	gramatas = list(map(int, input().split()))
	berni = [n for n in range(skaits)]
	rezultats = [0 for n in range(skaits)]
	for o in range(skaits):
		b = [0 for n in range(skaits)]
		for (i, gramata) in enumerate(berni):
			if gramatas[i] - 1 == gramata and rezultats[i] == 0:
				rezultats[i] = o + 1
			b[gramatas[i] - 1] = gramata
		berni = b
	print(' '.join(map(str, rezultats)))


q = int(input())
for _ in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	days = [0] * n
	for i in range(n):
		if a[i] != -1:
			loop = []
			loop.append(i)
			next_ = a[i] - 1
			a[i] = -1
			while next_ != loop[0]:
				loop.append(next_)
				prev = next_
				next_ = a[next_] - 1
				a[prev] = -1
			for j in range(len(loop)):
				days[loop[j]] = len(loop)
	for i in range(n):
		print(days[i], end=' ')
	print()


t = int(input())
for _ in range(t):
	n = int(input())
	l = [0] + list(map(int, input().split()))
	ans = []
	for i in range(1, n + 1):
		t = l[i]
		d = 1
		while t != i:
			d += 1
			t = l[t]
		ans.append(d)
	print(*ans)


import sys
from heapq import heapify, heappop, heappush
from itertools import *
from collections import *
from math import *
sys.setrecursionlimit(10 ** 6)
input = lambda : sys.stdin.readline()
inp = lambda : int(input())
nm = lambda : map(int, input().split())
arr = lambda : list(nm())
INF = int(1e+18)
mod = int(1000000000.0) + 7

def find(dp, n):
	while dp[n] > 0:
		n = dp[n]
	return n

def solve():
	n = inp()
	lst = arr()
	dp = [-1] * n
	for i in range(n):
		if lst[i] == i + 1:
			pass
		else:
			par1 = find(dp, i)
			par2 = find(dp, lst[i] - 1)
			if par1 < par2:
				dp[par2] = dp[par2] + dp[i]
				dp[i] = par2
			else:
				pass
	for i in range(n):
		print(-1 * dp[find(dp, i)], end=' ')
	print()
t = inp()
for i in range(t):
	solve()


import sys

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
sys.setrecursionlimit(10 ** 7)
INF = 10 ** 18
MOD = 10 ** 9 + 7

def rec(i, org, cnt):
	nxt = A[i]
	if nxt != org:
		cnt = rec(nxt, org, cnt + 1)
	ans[i] = cnt
	return cnt
for _ in range(INT()):
	N = INT()
	A = [a - 1 for a in LIST()]
	ans = [-1] * N
	for i in range(N):
		if ans[i] == -1:
			rec(i, i, 1)
	print(*ans)


for _ in ' ' * int(input()):
	a = int(input())
	b = [0] * a
	c = [int(i) - 1 for i in map(int, input().split())]
	for i in range(a):
		if c[i] == i:
			print(1, end=' ')
		elif b[i] == 0:
			k = i
			n = []
			while c[k] != i:
				b[c[k]] = i
				k = c[k]
				n += [c[k]]
			b[i] = n
			print(len(n) + 1, end=' ')
		else:
			print(len(b[b[i]]) + 1, end=' ')
	print()


q = int(input())
for i in range(q):
	n = int(input())
	ar = [int(ar) for ar in input().split(' ')]
	arr = []
	arr.append(0)
	for i in range(n):
		arr.append(ar[i])
	returnday = []
	for i in range(1, n + 1):
		x = i
		day = 0
		while True:
			if arr[x] == i:
				day += 1
				break
			else:
				day += 1
				x = arr[x]
		returnday.append(day)
	print(*returnday)


def find(a, b):
	if link[a] == link[b]:
		return True
	else:
		return False

def union(a, b):
	global link
	temp = link[a]
	for i in range(n):
		if link[i] == temp:
			link[i] = link[b]
for _ in range(int(input())):
	n = int(input())
	array = list(map(int, input().split()))
	link = [i for i in range(n)]
	for i in range(n):
		j = array[i] - 1
		union(i, j)
	this = {}
	for i in list(set(link)):
		this[i] = link.count(i)
	ans = []
	for i in link:
		ans.append(this[i])
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	ans = [0] * n
	for i in range(n):
		if not ans[i]:
			temp = arr[i] - 1
			s = set()
			s.add(temp)
			s.add(i)
			while temp != i:
				temp = arr[temp] - 1
				s.add(temp)
			for x in s:
				ans[x] = len(s)
	print(*ans)


def solve(n, p_s):
	ans = [0 for _ in range(n)]
	cur = [i + 1 for i in range(n)]
	next = [0 for _ in range(n)]
	for d in range(1, n + 1):
		for (i, p) in enumerate(p_s):
			next[p - 1] = cur[i]
			if ans[p - 1] == 0 and next[p - 1] == p:
				ans[p - 1] = str(d)
		cur = next.copy()
	return ' '.join(ans)
t = int(input())
for _ in range(t):
	n = int(input())
	p_s = [int(r) for r in input().split(' ')]
	print(solve(n, p_s))


q = int(input())
for i in range(q):
	n = int(input())
	l = [int(z) for z in input().split()]
	s = []
	for x in range(len(l)):
		pose = l[x]
		d = 1
		t = 1
		while pose != x + 1:
			pose = l[pose - 1]
			d += 1
		s.append(d)
	print(' '.join([str(y) for y in s]))


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	for i in range(n):
		start = arr[i]
		res = 1
		while start != i + 1:
			start = arr[start - 1]
			res += 1
		print(res, end=' ')
	print('')


import bisect
import collections as col
import functools as ft
import heapq
import itertools as it
import math
import os
import sys
sys.setrecursionlimit(10 ** 9)
input = sys.stdin.readline

def I():
	return int(input().strip())

def S():
	return [x for x in input().strip()]

def IL():
	return list(map(int, input().split()))

def SL():
	return list(map(str, input().split()))

def ILs(n):
	return list((int(input()) for _ in range(n)))

def SLs(n):
	return list((input().strip() for _ in range(n)))

def ILL(n):
	return [list(map(int, input().split())) for _ in range(n)]

def SLL(n):
	return [list(map(str, input().split())) for _ in range(n)]
MOD = 10 ** 9 + 7
INF = float('inf')

class DisjointSet:

	def __init__(self, n):
		self.parent = [i for i in range(n + 1)]
		self.rank = [1 for _ in range(n + 1)]

	def find(self, a):
		if self.parent[a] == a:
			return a
		self.parent[a] = self.find(self.parent[a])
		return self.parent[a]

	def union(self, a, b):
		(pa, pb) = (self.find(a), self.find(b))
		if pa == pb:
			return
		if self.rank[a] > self.rank[b]:
			self.parent[pb] = pa
			self.rank[pa] += self.rank[pb]
		else:
			self.parent[pa] = pb
			self.rank[pb] += self.rank[pa]

def main():
	for _ in range(I()):
		n = I()
		a = IL()
		g = col.defaultdict(list)
		for (i, val) in enumerate(a, start=1):
			g[i] = val
		uf = DisjointSet(n)
		for (k, v) in g.items():
			uf.union(k, v)
		ans = [uf.rank[uf.find(x)] for x in range(1, n + 1)]
		print(*ans)
main()


from sys import stdin, stdout
import bisect
import math
mod = 10 ** 9 + 7

def st():
	return list(stdin.readline().strip())

def inp():
	return int(stdin.readline())

def li():
	return list(map(int, stdin.readline().split()))

def mp():
	return map(int, stdin.readline().split())

def pr(n):
	stdout.write(str(n) + '\n')

def DFS(dictionary, vertex, visited):
	visited[vertex] = True
	stack = [vertex]
	print(vertex)
	while stack:
		a = stack.pop()
		for i in dictionary[a]:
			if not visited[i]:
				print(i)
				visited[i] = True
				stack.append(i)

def soe(limit):
	l = [1] * (limit + 1)
	l[0] = 0
	l[1] = 0
	prime = []
	for i in range(2, limit + 1):
		if l[i]:
			for j in range(i * i, limit + 1, i):
				l[j] = 0
	for i in range(2, limit + 1):
		if l[i]:
			prime.append(i)
	return prime

def segsoe(low, high):
	limit = int(high ** 0.5) + 1
	prime = soe(limit)
	n = high - low + 1
	l = [0] * (n + 1)
	for i in range(len(prime)):
		lowlimit = low // prime[i] * prime[i]
		if lowlimit < low:
			lowlimit += prime[i]
		if lowlimit == prime[i]:
			lowlimit += prime[i]
		for j in range(lowlimit, high + 1, prime[i]):
			l[j - low] = 1
	for i in range(low, high + 1):
		if not l[i - low]:
			if i != 1:
				print(i)

def gcd(a, b):
	while b:
		a = a % b
		(b, a) = (a, b)
	return a

def power(a, n):
	r = 1
	while n:
		if n & 1:
			r = r * a
		a *= a
		n = n >> 1
	return r

def solve():
	n = inp()
	l = li()
	l = [0] + l
	ans = [0] * (n + 1)
	visited = [0] * (n + 1)
	for i in range(1, n + 1):
		if not visited[i]:
			cur = []
			while not visited[i]:
				cur.append(i)
				visited[i] = True
				i = l[i]
			for i in cur:
				ans[i] = len(cur)
	print(*ans[1:])
for _ in range(inp()):
	solve()


from sys import stdin, stdout
q = int(input())
for _ in range(q):
	n = int(input())
	nums = list(map(int, stdin.readline().strip().split()))
	nums = [0] + nums
	ans = []
	for i in nums[1:]:
		count = 1
		found = nums[i]
		while found != i:
			found = nums[found]
			count += 1
		ans.append(count)
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	l = [0] * n
	for i in range(n):
		if l[i] == 0:
			t = [i]
			j = a[i]
			cnt = 1
			while j != i + 1:
				t.append(j - 1)
				j = a[j - 1]
				cnt += 1
			for u in t:
				l[u] = str(cnt)
	print(' '.join(l))


import sys
inf = sys.stdin

def main() -> None:
	q = int(inf.readline())
	while q > 0:
		a = [0] * 205
		n = int(inf.readline())
		sa = inf.readline().split()
		for i in range(n):
			a[i + 1] = int(sa[i])
		cur = [0] * 205
		day = [1] * 205
		done = [False] * 205
		t = 1
		for i in range(n + 1):
			cur[i] = a[i]
		identical = False
		while not identical:
			for i in range(1, n + 1):
				cur[i] = a[cur[i]]
			identical = True
			for i in range(1, n + 1):
				if not done[i]:
					if cur[i] != a[i]:
						identical = False
					else:
						done[i] = True
						day[i] = t
			t += 1
		for i in range(1, n + 1):
			print(day[i], end=' ')
		print()
		q -= 1
	return None
main()


from sys import stdin, stdout
input = stdin.readline

def fn(i, lst):
	count = 1
	j = lst[i]
	while not i == j:
		j = lst[j]
		count += 1
	return count
for kase in range(int(input())):
	input()
	lst = [int(x) - 1 for x in input().split()]
	ans = []
	for i in range(len(lst)):
		ans.append(fn(i, lst))
	print(*ans)


n = int(input())
l = []
for i in range(n):
	m = int(input())
	b = list(map(int, input().split()))
	o = [0] * m
	for j in range(m):
		x = j
		if o[j] == 0:
			v = []
			for k in range(m):
				if b[j] - 1 == x:
					v.append(j)
					for f in v:
						o[f] = k + 1
					k = m
					break
				else:
					v.append(j)
					j = b[j] - 1
	l.append(o)
for a in l:
	for s in range(len(a)):
		if s == len(a) - 1:
			print(a[s])
		else:
			print(a[s], end=' ')


q = int(input())
for i in range(q):
	n = int(input())
	p = [int(x) for x in input().split()]
	s = ''
	for i in range(len(p)):
		cnt = 1
		a = p[i]
		while a != i + 1:
			a = p[a - 1]
			cnt += 1
		s += str(cnt) + ' '
	print(s)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
import bisect
import heapq
from math import *
from collections import deque
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
mod = 1000000007

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def graph(vertex):
	return [[] for i in range(0, vertex + 1)]

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def lcm(a, b):
	return a * b // gcd(a, b)

def power(a, b):
	ans = 1
	while b > 0:
		if b % 2 == 1:
			ans *= a
		a *= a
		b //= 2
	return ans

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def solve():
	n = int(inp())
	a = lis()
	visited = [0] * (n + 1)
	cnt = [0] * n
	for i in range(0, n):
		if visited[i] == 0:
			visited[i] = 1
			arr = []
			curr = a[i]
			while curr != i + 1:
				visited[curr - 1] = 1
				arr.append(curr)
				curr = a[curr - 1]
			arr.append(i + 1)
			ll = len(arr)
			for j in range(0, ll):
				cnt[arr[j] - 1] = ll
	print(*cnt)
testcase(int(inp()))


a = [0] * 200010
fa = [0] * 200010
size = [0] * 200010

def f(x):
	if fa[x] == x:
		return x
	fa[x] = f(fa[x])
	return fa[x]
t = eval(input())
while t:
	t -= 1
	n = eval(input())
	for i in range(1, n + 1):
		fa[i] = i
		size[i] = 1
	a = list(map(int, input().split(' ')))
	for i in range(1, n + 1):
		if f(i) != f(a[i - 1]):
			size[f(a[i - 1])] += size[i]
			fa[f(i)] = f(a[i - 1])
	for i in range(1, n + 1):
		print(size[f(i)], end=' ')
	print()


def main():
	n = int(input())
	a = [0]
	a.extend(list(map(int, input().split())))
	arr = []
	for i in range(1, n + 1):
		if a[i] != i:
			temp = i
			cnt = 1
			while a[temp] != i:
				cnt += 1
				temp = a[temp]
			arr.append(cnt)
		else:
			arr.append(1)
	for x in arr:
		print(x, end=' ')
	print()
	return

def test():
	t = int(input())
	while t:
		main()
		t -= 1
test()


I = input
for _ in [0] * int(I()):
	r = [0] * int(I())
	a = (*map(int, I().split()),)
	s = {*a}
	while s:
		x = s.pop()
		t = [x]
		while a[x - 1] in s:
			x = a[x - 1]
			s -= {x}
			t += (x,)
		for x in t:
			r[x - 1] = len(t)
	print(*r)


import sys
input = sys.stdin.buffer.readline
from collections import defaultdict
INF = float('inf')

def getlist():
	return list(map(int, input().split()))

class UnionFind:

	def __init__(self, n):
		self.par = [i for i in range(n + 1)]
		self.rank = [0] * (n + 1)
		self.size = [1] * (n + 1)

	def find(self, x):
		if self.par[x] == x:
			return x
		else:
			self.par[x] = self.find(self.par[x])
			return self.par[x]

	def same_check(self, x, y):
		return self.find(x) == self.find(y)

	def union(self, x, y):
		x = self.find(x)
		y = self.find(y)
		if self.rank[x] < self.rank[y]:
			if self.same_check(x, y) != True:
				self.size[y] += self.size[x]
				self.size[x] = 0
			self.par[x] = y
		else:
			if self.same_check(x, y) != True:
				self.size[x] += self.size[y]
				self.size[y] = 0
			self.par[y] = x
			if self.rank[x] == self.rank[y]:
				self.rank[x] += 1

	def siz(self, x):
		x = self.find(x)
		return self.size[x]

def main():
	Q = int(input())
	for i in range(Q):
		N = int(input())
		p = getlist()
		UF = UnionFind(N)
		for i in range(N):
			UF.union(i, p[i] - 1)
		ans = [0] * N
		for i in range(N):
			ans[i] = UF.siz(i)
		print(' '.join(list(map(str, ans))))
main()


t = int(input())
for _ in range(t):
	n = int(input())
	x = list(map(int, input().split()))
	q = []
	for i in range(n):
		c = 1
		j = i + 1
		while x[j - 1] != i + 1:
			j = x[j - 1]
			c = c + 1
		q.append(c)
	print(*q)


for _ in range(int(input())):
	n = int(input())
	a = [0] + [int(x) for x in input().split()]
	vis = [0] * (n + 1)
	ans = [0] * (n + 1)
	for i in range(1, n + 1):
		if not vis[i]:
			conect = []
			while not vis[i]:
				conect.append(i)
				vis[i] = 1
				i = a[i]
			for i in conect:
				ans[i] = len(conect)
	ans.pop(0)
	print(*ans)


from itertools import *
q = int(input())
for _ in range(q):
	n = int(input())
	p = list(map(int, input().split()))
	m = [i + 1 for i in range(len(p))]
	n = [0 for i in range(len(p))]
	a = [i + 1 for i in range(len(p))]
	b = [0 for i in range(len(p))]
	for d in range(len(p)):
		for i in range(len(a)):
			b[p[i] - 1] = a[i]
		for i in range(len(a)):
			if not n[i] and b[i] == m[i]:
				n[i] = d + 1
		(a, b) = (b, a)
	print(*n)


for _ in range(int(input())):
	n = int(input())
	p = [int(i) - 1 for i in input().split()]
	kids = {}
	for kid in range(n):
		if kid in kids:
			continue
		kids_temp = set()
		d = 1
		i = kid
		kids_temp.add(i)
		while kid != p[i]:
			i = p[i]
			kids_temp.add(i)
			d += 1
		for i in kids_temp:
			kids[i] = d
	for i in range(n):
		print(kids[i], end=' ')
	print()


for x in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	ans = [0 for i in range(n)]
	adj = [[] for i in range(n)]
	vis = [0 for i in range(n)]

	def dfs(x, m):
		vis[x] = 1
		m += [x]
		flag = 0
		for i in adj[x]:
			if vis[i] != 1:
				flag = 1
				dfs(i, m)
		if flag == 0:
			ans[x] = m
	for i in range(n):
		adj[i] += [l[i] - 1]
		adj[l[i] - 1] += [i]
	for i in range(n):
		if vis[i] != 1:
			dfs(i, [])
	op = [0 for i in range(n)]
	for i in ans:
		if i != 0:
			f = len(i)
			for j in i:
				op[j] = f
	for i in op:
		print(i, end=' ')
	print()


q = int(input())
answer = []
for i in range(q):
	n = int(input())
	arr = list(map(int, input().split()))
	ans = []
	for j in range(n):
		answ = 1
		temp = j
		k = j
		while arr[k] - 1 != temp:
			k = arr[k] - 1
			answ += 1
		ans.append(answ)
	answer.append(ans)
for i in range(q):
	print(*answer[i], sep=' ')


import sys
lg = 0
viz = []
v = []

def test():
	global lg, v, viz
	n = int(input())
	v = [int(x) - 1 for x in input().split()]
	viz = [0 for i in range(n)]
	ans = [0 for i in range(n)]
	for i in range(n):
		if not viz[i]:
			lg = 0
			(lst, p) = ([], i)
			while not viz[p]:
				lst.append(p)
				viz[p] = 1
				p = v[p]
				lg += 1
			for x in lst:
				ans[x] = lg
	print(' '.join([str(i) for i in ans]))
t = int(input())
for _ in range(t):
	test()