A permutation — is a sequence of length $n$ integers from $1$ to $n$, in which all the numbers occur exactly once. For example, $[1]$, $[3, 5, 2, 1, 4]$, $[1, 3, 2]$ — permutations, and $[2, 3, 2]$, $[4, 3, 1]$, $[0]$ — no.

Polycarp was recently gifted a permutation $a[1 \dots n]$ of length $n$. Polycarp likes trees more than permutations, so he wants to transform permutation $a$ into a rooted binary tree. He transforms an array of different integers into a tree as follows:

the maximum element of the array becomes the root of the tree;

all elements to the left of the maximum — form a left subtree (which is built according to the same rules but applied to the left part of the array), but if there are no elements to the left of the maximum, then the root has no left child;

all elements to the right of the maximum — form a right subtree (which is built according to the same rules but applied to the right side of the array), but if there are no elements to the right of the maximum, then the root has no right child.

For example, if he builds a tree by permutation $a=[3, 5, 2, 1, 4]$, then the root will be the element $a_2=5$, and the left subtree will be the tree that will be built for the subarray $a[1 \dots 1] = [3]$, and the right one — for the subarray $a[3 \dots 5] = [2, 1, 4]$. As a result, the following tree will be built:

The tree corresponding to the permutation $a=[3, 5, 2, 1, 4]$.

Another example: let the permutation be $a=[1, 3, 2, 7, 5, 6, 4]$. In this case, the tree looks like this:

The tree corresponding to the permutation $a=[1, 3, 2, 7, 5, 6, 4]$.

Let us denote by $d_v$ the depth of the vertex $a_v$, that is, the number of edges on the path from the root to the vertex numbered $a_v$. Note that the root depth is zero. Given the permutation $a$, for each vertex, find the value of $d_v$.


-----Input-----

The first line contains one integer $t$ ($1 \le t \le 100$) — the number of test cases. Then $t$ test cases follow.

The first line of each test case contains an integer $n$ ($1 \le n \le 100$) — the length of the permutation.

This is followed by $n$ numbers $a_1, a_2, \ldots, a_n$ — permutation $a$.


-----Output-----

For each test case, output $n$ values — $d_1, d_2, \ldots, d_n$.


-----Examples-----

Input
3
5
3 5 2 1 4
1
1
4
4 3 1 2
Output
1 0 2 3 1 
0 
0 1 3 2


-----Note-----

None

Source: codeforces | Difficulty: EASY
Tags: Graph traversal

Implementation

Divide and conquer


Solutions:
t = int(input())

def depth(a, ans, lower, upper, lvl):
	try:
		l = max(a[lower:upper])
		ind = a.index(l)
		ans[ind] = str(lvl)
		depth(a, ans, lower, ind, lvl + 1)
		depth(a, ans, ind + 1, upper, lvl + 1)
		return
	except:
		return
for testcase in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [0 for _ in range(n)]
	depth(a, ans, 0, n, 0)
	print(' '.join(ans))


def found_depth_tree(start, end, depth, ls, cnt):
	if start > end:
		return
	if start == end:
		depth[start] = cnt
	max_ind = start
	for i in range(start + 1, end + 1):
		if ls[max_ind] < ls[i]:
			max_ind = i
	depth[max_ind] = cnt
	found_depth_tree(start, max_ind - 1, depth, ls, cnt + 1)
	found_depth_tree(max_ind + 1, end, depth, ls, cnt + 1)
	return
t = int(input())
for _ in range(t):
	n = int(input())
	ls = [int(i) for i in input().split()]
	depth = [-1 for i in range(n)]
	found_depth_tree(0, n - 1, depth, ls, 0)
	print(*depth)


def nr():
	return nrs()[0]

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

def f(a, l=0):
	if len(a) == 0:
		return []
	i = a.index(max(a))
	return f(a[:i], l + 1) + [l] + f(a[i + 1:], l + 1)
for i in range(nr()):
	n = nrs()
	print(*f(nrs()))


def work(n, a):
	res = [0] * n

	def dfs(l, r, depth):
		if l > r:
			return
		if l == r:
			res[l] = depth
			return
		(maxv, idx) = (0, -1)
		for i in range(l, r + 1):
			if a[i] > maxv:
				maxv = a[i]
				idx = i
		res[idx] = depth
		dfs(l, idx - 1, depth + 1)
		dfs(idx + 1, r, depth + 1)
		return
	dfs(0, n - 1, 0)
	return res

def main():
	test = int(input())
	for _ in range(test):
		n = int(input())
		a = list(map(int, input().split()))
		ans = work(n, a)
		print(*ans)
	return
main()


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

	def go(v, h):
		if v:
			x = max(v)
			i = v.index(x)
			d[x] = h
			go(v[:i], h + 1)
			go(v[i + 1:], h + 1)
	go(a, 0)
	print(*(d[a[i]] for i in range(n)))


cases = int(input())
ans_list = []
for _ in range(cases):
	n = int(input())
	a = list(map(int, input().split(' ')))
	depth = [0 for i in range(n + 1)]

	def rec(arr, cur_depth):
		if len(arr) == 0:
			return
		pivot = arr.index(max(arr))
		depth[arr[pivot]] = cur_depth
		rec(arr[:pivot], cur_depth + 1)
		rec(arr[pivot + 1:], cur_depth + 1)
	rec(a, 0)
	cur_ans = []
	for val in a:
		cur_ans.append(depth[val])
	ans_list.append(cur_ans)
for arr in ans_list:
	print(' '.join(map(str, arr)))


import sys
input = sys.stdin.readline

def build_binary_tree(l, r, d):
	if l > r:
		return
	if l == r:
		depths[l] = d
		return
	pivot = values[l:r + 1].index(max(values[l:r + 1])) + l
	depths[pivot] = d
	build_binary_tree(l, pivot - 1, d + 1)
	build_binary_tree(pivot + 1, r, d + 1)
for _ in range(int(input())):
	(n, values, depths) = (int(input()), [int(i) for i in input().split()], [-1 for _ in range(101)])
	build_binary_tree(0, n - 1, 0)
	print(*depths[:n])


import sys
input = sys.stdin.readline

def dfs(p, arr, d):
	if not arr:
		return
	m = max(arr)
	x = arr.index(m)
	a = arr[:x]
	b = arr[x + 1:]
	ans[p + x] = d
	dfs(p, a, d + 1)
	dfs(p + x + 1, b, d + 1)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [0] * n
	dfs(0, a, 0)
	print(*ans)


t = int(input())

def getmax(lst: list):
	ans = lst[0]
	for e in lst:
		if e > ans:
			ans = e
	return ans

def getmaxidx(a, arr):
	max_ = getmax(a)
	return (arr.index(max_), max_)

def maketree(left: list, right: list, depth, ans: list, arr):
	if len(left) == 0 and len(right) == 0:
		return
	if len(left) != 0:
		(lstart, lmax) = getmaxidx(left[:], arr)
		ans[lstart] = depth
		maketree(left[:left.index(lmax)], left[left.index(lmax) + 1:], depth=depth + 1, ans=ans, arr=arr)
	if len(right) != 0:
		(rstart, rmax) = getmaxidx(right[:], arr)
		ans[rstart] = depth
		maketree(right[:right.index(rmax)], right[right.index(rmax) + 1:], depth=depth + 1, ans=ans, arr=arr)
for _ in range(t):
	n = int(input())
	ans = [0] * n
	arr = list(map(int, input().split(' ')))
	(start, max) = getmaxidx(arr, arr)
	depth = 0
	ans[start] = depth
	maketree(arr[:start], arr[start + 1:], depth=depth + 1, ans=ans, arr=arr)
	print(*ans)


import sys
input = sys.stdin.readline

def tree(a, base):
	if len(a) == 0:
		return
	if len(a) == 1:
		return [base]
	temp = a.index(max(a))
	ans = [base for x in range(len(a))]
	temp1 = tree(a[:temp], base + 1)
	temp2 = tree(a[temp + 1:], base + 1)
	temp = 0
	if temp1:
		for i in temp1:
			ans[temp] = i
			temp += 1
	temp += 1
	if temp2:
		for i in temp2:
			ans[temp] = i
			temp += 1
	return ans
t = int(input())
for i in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	base = 0
	ans = tree(a, 0)
	ans = [str(i) for i in ans]
	print(' '.join(ans))


def bin_search(ans, halp, a, b):
	if len(a) > 0:
		m = a.index(max(a))
		ind = halp.index(max(a))
		b[ind] = ans
		p = a[:m]
		q = a[m + 1:]
		bin_search(ans + 1, halp, p, b)
		bin_search(ans + 1, halp, q, b)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = [0 for i in range(n)]
	halp = a.copy()
	ans = 0
	bin_search(ans, halp, a, b)
	print(*b)


import sys
import math
from collections import defaultdict, Counter, deque
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')

def find(l, lev):
	if len(l) == 0:
		return
	ma = max(l)
	ans[d[ma]] = lev
	ind = l.index(ma)
	find(l[:ind], lev + 1)
	find(l[ind + 1:], lev + 1)
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	d = {}
	for j in range(n):
		d[a[j]] = j
	ans = [0] * n
	find(a, 0)
	print(*ans)


def solveTree(nodes, depth=0):
	if len(nodes) == 1:
		return [depth]
	if not len(nodes):
		return []
	max_el = max(nodes)
	max_in = nodes.index(max_el)
	left = nodes[:max_in]
	right = nodes[max_in + 1:]
	res = [-1] * len(nodes)
	res = solveTree(left, depth + 1) + [depth] + solveTree(right, depth + 1)
	return res
t = int(input())
for _ in range(t):
	N = int(input())
	nodes = list(map(int, input().split()))
	for i in solveTree(nodes):
		print(i, end=' ')
	print()


import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
(t,) = I()
for _ in range(t):
	(n,) = I()
	l = I()
	an = [0] * n
	for i in range(n):
		x = y = 0
		j = i + 1
		x = l[i]
		while j < n:
			if l[j] > x:
				an[i] += 1
				x = l[j]
			if l[j] == n:
				break
			j += 1
		j = i - 1
		x = l[i]
		while j > -1:
			if l[j] > x:
				an[i] += 1
				x = l[j]
			if l[j] == n:
				break
			j -= 1
	print(*an)


def tree(res, m, d=0):
	if len(m) == 1:
		res[m[0][0]] = d
	elif len(m) > 1:
		max_m = m[0]
		max_i = 0
		for j in range(len(m)):
			if m[j][1] > max_m[1]:
				max_m = m[j]
				max_i = j
		res[max_m[0]] = d
		tree(res, m[:max_i], d + 1)
		tree(res, m[max_i + 1:], d + 1)

def find():
	n = int(input())
	mas = tuple(enumerate(map(int, input().split())))
	res = [0] * n
	tree(res, mas)
	return res
for i in range(int(input())):
	print(*find())


t = int(input())
while t:
	t -= 1
	n = int(input())
	arr = list(map(int, input().split()))
	res = [0] * n

	def f(start, end, depth):
		if start > end:
			return
		x = max(arr[start:end + 1])
		index = arr.index(x)
		res[index] = depth
		f(start, index - 1, depth + 1)
		f(index + 1, end, depth + 1)
	f(0, n - 1, 0)
	print(*res)


n = int(input())

def divide(arr):
	max_ind = 0
	for i in range(len(arr)):
		if arr[i] > arr[max_ind]:
			max_ind = i
	return (arr[max_ind], arr[:max_ind], arr[max_ind + 1:])

def conquer(arr, ans, hash_map, depth):
	(max_num, left, right) = divide(arr)
	ind = hash_map[max_num]
	ans[ind] = depth
	if len(left) > 0:
		conquer(left, ans, hash_map, depth + 1)
	if len(right) > 0:
		conquer(right, ans, hash_map, depth + 1)
for _ in range(n):
	length = int(input())
	arr = list(map(int, input().split()))
	ans = [0] * length
	depth = 0
	hash_map = {}
	for (i, val) in enumerate(arr):
		hash_map[val] = i
	conquer(arr, ans, hash_map, depth)
	print(' '.join(map(str, ans)))


def dfs(l, d, c):
	if l:
		m = max(l)
		ind = l.index(m)
		d[m] = c
		d = dfs(l[:ind], d, c + 1)
		d = dfs(l[ind + 1:], d, c + 1)
	return d
for _ in range(int(input())):
	n = int(input())
	c = 0
	l = list(map(int, input().split()))
	ans = dfs(l, {}, 0)
	res = []
	for i in l:
		res.append(ans[i])
	print(*res)


testcases = int(input())
import sys

def get_ints():
	return list(map(int, sys.stdin.readline().strip().split()))
dicts = {}

def dfs(newarr, lvl):
	global dicts
	newarrlen = len(newarr)
	if newarrlen == 0:
		return
	maxs = max(newarr)
	maxsindex = newarr.index(maxs)
	if newarrlen == 1:
		dicts[maxs] = lvl + 1
		return
	dicts[maxs] = lvl + 1
	dfs(newarr[:maxsindex], lvl + 1)
	dfs(newarr[maxsindex + 1:], lvl + 1)
for testcase in range(testcases):
	n = int(input())
	arr = get_ints()
	maxs = max(arr)
	maxsindex = arr.index(maxs)
	dicts[maxs] = 0
	newlef = arr[:maxsindex]
	newright = arr[maxsindex + 1:]
	dfs(arr[:maxsindex], 0)
	dfs(arr[maxsindex + 1:], 0)
	ans = []
	for i in arr:
		if i in dicts:
			ans.append(str(dicts[i]))
	print(' '.join(ans))


def bs(a):
	if len(a) <= 1:
		return [0]
	mid = a.index(max(a))
	dp = [-1 for _ in a]
	dp[:mid] = bs(a[:mid])
	dp[mid] = -1
	dp[mid + 1:] = bs(a[mid + 1:])
	dp = [n + 1 for n in dp]
	return dp[:len(a)]
T = int(input())
for _ in range(T):
	N = int(input())
	p = list(map(int, input().split()))
	print(*bs(p))


def find_max(l, i, j):
	current_max = l[i]
	current_max_index = i
	for k in range(i, j + 1):
		if current_max < l[k]:
			current_max = l[k]
			current_max_index = k
	return current_max_index

def recursive_function(level, l, final_l, start, end):
	if start > end:
		return
	else:
		current_index = find_max(l, start, end)
		final_l[current_index] = level
		recursive_function(level + 1, l, final_l, start, current_index - 1)
		recursive_function(level + 1, l, final_l, current_index + 1, end)

def main_function():
	test_cases = range(int(input()))
	for test_case in test_cases:
		n = int(input())
		a = [int(i) for i in input().split(' ')]
		final_a = [0 for i in range(n)]
		recursive_function(0, a, final_a, 0, len(a) - 1)
		print(' '.join([str(i) for i in final_a]))
main_function()


def helper(A, level, ans, k):
	if len(A) == 0:
		return
	max_index = A.index(max(A))
	ans[k + max_index] = level
	helper(A[:max_index], level + 1, ans, k)
	helper(A[max_index + 1:], level + 1, ans, max_index + 1 + k)
	return ans
for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [0] * len(a)
	ans = helper(a, 0, ans, 0)
	print(*ans)


def fun(arr, path, start_index, end_index):
	if start_index >= end_index:
		return
	main_index = arr.index(max(arr[start_index:end_index]))
	d[main_index] = path
	path += 1
	fun(arr, path, start_index, main_index)
	fun(arr, path, main_index + 1, end_index)
b = []
t = int(input())
global d
for i in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	d = [0 for i in range(n)]
	fun(a, 0, 0, len(a))
	b.append(d)
[print(*i) for i in b]


get_line = lambda type_: list(map(type_, input().strip().split()))

def helper(per, depth, start, end, ans):
	if start > end:
		return
	max_index = start
	for i in range(start + 1, end + 1):
		if per[i] > per[max_index]:
			max_index = i
	ans[max_index] = str(depth)
	helper(per, depth + 1, start, max_index - 1, ans)
	helper(per, depth + 1, max_index + 1, end, ans)

def solve():
	n = int(input())
	a = get_line(int)
	ans = [0] * n
	helper(a, 0, 0, n - 1, ans)
	print(' '.join(ans))
t = int(input())
for _ in range(t):
	solve()


import os
import sys
from collections import defaultdict
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')
readint = lambda : int(sys.stdin.readline().rstrip('\r\n'))
readints = lambda : map(int, sys.stdin.readline().rstrip('\r\n').split())
readstr = lambda : sys.stdin.readline().rstrip('\r\n')
readstrs = lambda : map(str, sys.stdin.readline().rstrip('\r\n').split())
readarri = lambda : [int(_) for _ in sys.stdin.readline().rstrip('\r\n').split()]
readarrs = lambda : [str(_) for _ in sys.stdin.readline().rstrip('\r\n').split()]
sys.setrecursionlimit(100 * 100 * 100)
mod = 998244353
MOD = int(1000000000.0) + 7
ans = [0] * 101
idx = defaultdict(int)

def clear_global():
	global ans, idx
	idx.clear()
	ans = [0] * 101

def chaalu(arr, depth, left, right):
	if len(arr) == 0:
		return
	maxx = max(arr)
	check = arr.index(maxx)
	ans[idx[maxx]] = depth
	chaalu(arr[:check], depth + 1, left, left + check - 1)
	chaalu(arr[check + 1:], depth + 1, left + check + 1, right)

def solve():
	(n, ar) = (readint(), readarri())
	for i in range(n):
		idx[ar[i]] = i
	chaalu(ar, 0, 0, n - 1)
	print(*ans[0:n])

def main():
	t = 1
	t = readint()
	for _ in range(t):
		solve()
main()


class Node(object):

	def __init__(self, val):
		self.left = None
		self.right = None
		self.val = val

def perm_to_tree(d, level, node, a):
	if a == []:
		return
	idx = a.index(max(a))
	d[a[idx]] = level
	node = Node(a[idx])
	perm_to_tree(d, level + 1, node.left, a[:idx])
	perm_to_tree(d, level + 1, node.right, a[idx + 1:])
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	root = None
	d = {}
	perm_to_tree(d, 0, root, a)
	ans = [0] * n
	for i in range(n):
		ans[i] = d[a[i]]
	print(*ans)


class Tree:

	def __init__(self, val):
		self.val = val
		self.left = None
		self.right = None

def construct(l, dmap, curr_depth):
	if len(l) == 0:
		return None
	mx = max(l)
	dmap[mx] = curr_depth
	mx_idx = l.index(mx)
	root = Tree(mx)
	root.left = construct(l[:mx_idx], dmap, curr_depth + 1)
	root.right = construct(l[mx_idx + 1:], dmap, curr_depth + 1)
	return root
t = int(input())
for _ in range(t):
	n = int(input())
	l = list((int(num) for num in input().strip().split()))[:n]
	dmap = dict()
	root = construct(l, dmap, 0)
	for item in l:
		print(dmap[item], end=' ')
	print()


def busca(d, right, left):
	if right <= left:
		index = right
		maior_n = 0
		while index <= left:
			if a[index] > maior_n:
				maior_n = a[index]
				maior_i = index
			index += 1
		a[maior_i] = d
		busca(d + 1, maior_i + 1, left)
		busca(d + 1, right, maior_i - 1)
t = int(input())
for i in range(t):
	n = int(input())
	a = input().split(' ')
	for i in range(n):
		a[i] = int(a[i])
	busca(0, 0, n - 1)
	for i in a:
		print(i, end=' ')
	print()


def cal(a, left, right, memo, d=0):
	if a[left:right] == []:
		return
	m = max(a[left:right])
	memo[a.index(m)] = d
	b = a.index(m)
	cal(a, left, b, memo, d + 1)
	cal(a, b + 1, right, memo, d + 1)
	return
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	memo = [0 for _ in range(n)]
	left = 0
	right = n
	cal(l, left, right, memo)
	print(' '.join(map(str, memo)))


ak = int(input())
for i in range(ak):
	dh = input()
	alpha = input()
	beta = alpha.split(' ')
	x = [int(beta[i]) for i in range(len(beta))]
	a = [-1 for i in range(len(x))]
	MAXIN = 0
	for i in range(len(x)):
		if x[i] == len(x):
			MAXIN = i
			break
		else:
			pass
	a[MAXIN] = 0
	k = len(x) - 1
	addition = 0
	while k != 0:
		maxi = -1
		index = -1
		addition += 1
		for i in range(len(x)):
			if a[i] != -1 and i != 0 and (index != -1):
				a[index] = addition
				maxi = 0
				index = -1
				k -= 1
			elif a[i] != -1 and i == 0:
				index = -1
			elif a[i] != -1 and index == -1:
				pass
			elif i == len(x) - 1 and maxi < x[i]:
				a[i] = addition
				k -= 1
			elif i == len(x) - 1 and maxi > x[i]:
				a[index] = addition
				k -= 1
			elif maxi < x[i]:
				maxi = x[i]
				index = i
			else:
				pass
	s = ''
	for i in range(len(a)):
		s = s + str(a[i]) + ' '
	print(s)


def sol(nums, begin, end, depth):
	if end - begin < 1:
		return
	curNums = nums[begin:end]
	i = nums.index(max(curNums))
	ans[i] = depth
	sol(nums, begin, i, depth + 1)
	sol(nums, i + 1, end, depth + 1)
t = int(input())
for _ in range(t):
	n = int(input())
	nums = list(map(int, input().split()))
	ans = [0] * n
	sol(nums, 0, n, 0)
	print(' '.join(map(str, ans)))


t = int(input().strip())
for _ in range(t):
	n = int(input().strip())
	a = [int(i) for i in input().strip().split()]
	mv = max(a)
	mi = a.index(mv)
	o = ['0'] * n
	q = []
	if mi > 0:
		q.append((1, 0, mi - 1))
	if mi < n - 1:
		q.append((1, mi + 1, n - 1))
	while len(q) > 0:
		(d, ini, end) = q.pop(0)
		mv = max(a[ini:end + 1])
		mi = a.index(mv)
		o[mi] = f'{d}'
		if mi > ini:
			q.append((d + 1, ini, mi - 1))
		if mi < end:
			q.append((d + 1, mi + 1, end))
	print(' '.join(o))


def add_nodes(permutacao, profundidade, lista_nos):
	max_value = max(permutacao)
	max_index = permutacao.index(max_value)
	lista_nos[max_value - 1] = profundidade
	profundidade += 1
	if max_index != 0:
		add_nodes(permutacao[:max_index], profundidade, lista_nos)
	if max_index != len(permutacao) - 1:
		add_nodes(permutacao[max_index + 1:], profundidade, lista_nos)
n_testes = input()
for i in range(int(n_testes)):
	n_elements = input()
	permutacao = list(map(int, input().split()))
	nos = [0] * int(n_elements)
	add_nodes(permutacao, 0, nos)
	result = ''
	for j in permutacao:
		result += str(nos[j - 1]) + ' '
	print(result)


def max_index(a, l, r):
	idx = l
	mx = a[l]
	for i in range(l, r + 1):
		if a[i] > mx:
			idx = i
			mx = a[i]
	return idx

class Node:

	def __init__(self, data=None, left=None, right=None, depth=-1):
		self.left = left
		self.right = right
		self.data = data
		self.depth = depth

def create_perm_tree(a, l, r, d, node_map):
	if r - l < 0 or len(node_map) == len(a):
		return None
	mx_i = max_index(a, l, r)
	nd = Node()
	nd.data = a[mx_i]
	nd.depth = d
	create_perm_tree(a, l, mx_i - 1, d + 1, node_map)
	create_perm_tree(a, mx_i + 1, r, d + 1, node_map)
	node_map[mx_i] = nd.depth
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	node_map = {}
	create_perm_tree(a, 0, n - 1, 0, node_map)
	res = []
	for i in range(n):
		res.append(node_map[i])
	print(' '.join((str(r) for r in res)))


def tree(arr, cnt):
	if not arr:
		return
	mx = max(arr)
	d[mx] = cnt
	ind = arr.index(mx)
	tree(arr[:ind], cnt + 1)
	tree(arr[ind + 1:], cnt + 1)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	d = dict()
	tree(a, 0)
	for i in a:
		print(d[i], end=' ')
	print()


def no_of_edges(A, n, levels, l, u, k):
	if l <= u:
		index = l
		maxi = A[l]
		for i in range(l, u + 1):
			if A[i] > maxi:
				maxi = A[i]
				index = i
		levels[index] = k
		no_of_edges(A, n, levels, l, index - 1, k + 1)
		no_of_edges(A, n, levels, index + 1, u, k + 1)
	else:
		return levels
	return levels
t = int(input())
for i in range(t):
	n = int(input())
	A = [int(i) for i in input().split()]
	levels = []
	for i in range(n):
		levels.append(0)
	levels = no_of_edges(A, n, levels, 0, n - 1, 0)
	for i in levels:
		print(i, end=' ')
	print()


from collections import deque
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	maxi = 0
	indx = 0
	for i in range(n):
		if maxi < a[i]:
			maxi = a[i]
			indx = i
	visited = [0 for i in range(n + 1)]
	queue = deque()
	queue.append([maxi, indx])
	visited[indx] = 1
	stored = [0 for i in range(n + 1)]
	while queue:
		(q, idx) = queue.popleft()
		visited[idx] = 1
		maxi = 0
		indx = idx
		indx -= 1
		indxe = 0
		while indx >= 0 and visited[indx] == 0:
			if maxi < a[indx]:
				maxi = max(maxi, a[indx])
				indxe = indx
			indx -= 1
		if maxi > 0:
			queue.append([maxi, indxe])
			stored[maxi] = stored[q] + 1
		maxi = 0
		indx = idx
		indx += 1
		while indx < n and visited[indx] == 0:
			if maxi < a[indx]:
				maxi = max(maxi, a[indx])
				indxe = indx
			indx += 1
		if maxi > 0:
			queue.append([maxi, indxe])
			stored[maxi] = stored[q] + 1
	for i in range(n):
		print(stored[a[i]], end=' ')
	print()


def pinpin(l, r, d, ans, a):
	if l > r:
		return
	x = max(a[l:r + 1])
	if x == -1:
		return
	pos_x = a.index(x)
	a[pos_x] = -1
	ans[pos_x] = d
	pinpin(l, pos_x - 1, d + 1, ans, a)
	pinpin(pos_x + 1, r, d + 1, ans, a)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [-1] * n
	pinpin(0, n - 1, 0, ans, a)
	print(*ans)


def f(l, r, g):
	if l > r:
		return
	maxx = l
	for i in range(l + 1, r + 1):
		if a[maxx] < a[i]:
			maxx = i
	d[maxx] = g
	f(l, maxx - 1, g + 1)
	f(maxx + 1, r, g + 1)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	d = [0] * n
	f(0, n - 1, 0)
	print(*d)


def depth(a, i):
	mi = a.index(max(a))
	if i == mi:
		return 0
	elif i < mi:
		return 1 + depth(a[:mi], i)
	else:
		return 1 + depth(a[mi + 1:], i - (mi + 1))

def foo(a):
	return [depth(a, i) for i in range(len(a))]

def main():
	t = int(input())
	for case in range(t):
		n = int(input())
		a = input()
		a = [int(i) for i in a.split()]
		print(' '.join([str(i) for i in foo(a)]))
main()


def permutation_transformation(A, l, r, d, D):
	m = l
	i = l
	while i <= r:
		if A[i] > A[m]:
			m = i
		i += 1
	if l < m:
		permutation_transformation(A, l, m - 1, d + 1, D)
	print(d, end=' ')
	if m < r:
		permutation_transformation(A, m + 1, r, d + 1, D)
t = int(input())
for i in range(t):
	n = int(input())
	A = list(map(int, input().split(' ')))
	D = [0 for _ in range(n)]
	permutation_transformation(A, 0, n - 1, 0, D)
	print()


rn = lambda : int(input())
rns = lambda : map(int, input().split())
rl = lambda : list(map(int, input().split()))
rs = lambda : input()
YN = lambda x: print('YES') if x else print('NO')
mod = lambda x: x % (10 ** 9 + 7)

def d(a):
	d = {}
	for i in a:
		if i not in d:
			d[i] = 0
		d[i] += 1
	return d
for _ in range(rn()):
	n = rn()
	l = rl()
	ans = n * [0]

	def solve(arr, ans, add):
		if len(arr) == 0:
			return 0
		ans[max(arr) - 1] = add
		i = arr.index(max(arr))
		solve(arr[:i], ans, add + 1)
		solve(arr[i + 1:], ans, add + 1)
	solve(l, ans, 0)
	tans = []
	for i in l:
		tans.append(ans[i - 1])
	print(*tans)


def permutTransf(a, level):
	if len(a) == 0:
		return []
	if len(a) == 1:
		return [level]
	z = a.index(max(a))
	x = permutTransf(a[:z], level + 1)
	y = permutTransf(a[z + 1:], level + 1)
	return x + [level] + y
for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	print(*permutTransf(a, 0))


def ass(a, b):
	print(f'Assertion error: {a} != {b}' if a != b else 'OK')

def nr():
	return nrs()[0]

def nrs():
	return [int(item) for item in input().split()]

def word():
	return input()

def words():
	return [item for item in input().split()]

def dump(lst):
	for (i, item) in enumerate(lst):
		print(i, item)

def binsearch(arr, a, b):
	m = (a + b) // 2
	if a >= b:
		return a - 1 if arr[a] == 0 else a
	return binsearch(arr, a, m - 1) if arr[m] == 0 else binsearch(arr, m + 1, b)

def gcd(x, y):
	return x if y == 0 else gcd(y, x % y)

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

def f(arr, level=0):
	if len(arr) == 0:
		return []
	m = max(arr)
	i = arr.index(m)
	return f(arr[:i], level + 1) + [level] + f(arr[i + 1:], level + 1)
for i in range(nr()):
	n = nrs()
	print(*f(nrs()))


import sys

def solve(vet, dic={}, d=0):
	if len(vet) == 0:
		return {}
	maximo = max(vet)
	ind = vet.index(maximo)
	dicEsq = solve(vet[0:ind], d=d + 1)
	dicDir = solve(vet[ind + 1:], d=d + 1)
	dicMax = {maximo: d}
	ret = {**dicEsq, **dicMax, **dicDir}
	return ret

def printRes(res):
	ret = ''
	for i in res:
		ret += str(res[i]) + ' '
	print(ret.strip())
l = sys.stdin.readlines()
t = int(l[0].replace('\n', ''))
i = 1
for _ in range(t):
	n = int(l[i].replace('\n', ''))
	i += 1
	a = [int(x) for x in l[i].replace('\n', '').split()]
	i += 1
	res = solve(a)
	printRes(res)


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
import copy
import time
starttime = time.time()
mod = int(pow(10, 9) + 7)
mod2 = 998244353

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

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def L():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
try:
	sys.stdin = open('input.txt', 'r')
except:
	pass

def pmat(A):
	for ele in A:
		print(*ele, end='\n')

def rec(i, j, level):
	if i > j:
		return
	if i == j:
		d[i + 1] = level
		return
	x = A.index(max(A[i:j + 1]))
	if not i <= x <= j:
		return
	d[x + 1] = level
	rec(i, x - 1, level + 1)
	rec(x + 1, j, level + 1)
for _ in range(L()[0]):
	n = L()[0]
	A = L()
	d = [0 for i in range(n + 1)]
	rec(0, n - 1, 0)
	print(*d[1:])
endtime = time.time()


import sys
rd = sys.stdin.readline

def conq(a, b, res, label):
	if len(b) == 0:
		return res
	x = a.index(max(b))
	x1 = b.index(max(b))
	res[x] = label
	conq(a, b[:x1], res, label + 1)
	conq(a, b[x1 + 1:], res, label + 1)
	return res
for _ in range(int(rd())):
	n = int(rd())
	a = list(map(int, rd().split()))
	res = [0] * n
	print(' '.join(map(str, conq(a, a, res, 0))))


import os
import sys
import math
from io import BytesIO, IOBase
input = sys.stdin.readline

def inp():
	return int(input())

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

def insr():
	s = input()
	return list(s[:len(s) - 1])

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

def dijkstra(start, distance, path, n):
	visited = [False for _ in range(n)]
	distance[start] = 0
	for i in range(n):
		v = -1
		for j in range(n):
			if not visited[v] and (v == -1 or distance[j] < distance[v]):
				v = j
		if distance[v] == math.inf:
			break
		visited[v] = True
		for edge in adj[v]:
			destination = edge[0]
			weight = edge[1]
			if distance[v] + weight < distance[destination]:
				distance[destination] = distance[v] + weight
				path[destination] = v

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

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

def ncr(n, r):
	return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

def npr(n, r):
	return math.factorial(n) // math.factorial(n - r)

def seive(n):
	primes = [True] * (n + 1)
	ans = []
	for i in range(2, n):
		if not primes[i]:
			continue
		j = 2 * i
		while j <= n:
			primes[j] = False
			j += i
	for p in range(2, n + 1):
		if primes[p]:
			ans += [p]
	return ans

def factors(n):
	factors = []
	x = 1
	while x * x <= n:
		if n % x == 0:
			if n // x == x:
				factors.append(x)
			else:
				factors.append(x)
				factors.append(n // x)
		x += 1
	return factors

def main():
	try:
		for _ in range(inp()):
			n = inp()
			a = inlt()
			arr = [0] * n

			def solve(d, l, r):
				if l <= r:
					mx = a.index(max(a[l:r + 1]))
					arr[mx] = d + 1
				else:
					return
				solve(d + 1, l, mx - 1)
				solve(d + 1, mx + 1, r)
			solve(-1, 0, n - 1)
			print(*arr, sep=' ')
	except Exception as e:
		print(e)
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')
main()


def node(ind, stuff, lvl):
	if ind[0] - ind[1] != 0:
		most = max(a[ind[0]:ind[1]])
		inds = a.index(most)
		ind = [[ind[0], inds], [inds + 1, ind[1]]]
		stuff[inds] = lvl
		for i in reversed(range(len(ind))):
			if i == 1:
				lvl += 1
			stuff = node(ind[i], stuff, lvl)
	return stuff
t = int(input())
for u in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	stuff = [-1] * len(a)
	rights = []
	stuff = node([0, len(a)], stuff, 0)
	stuff = [str(x) for x in stuff]
	print(' '.join(stuff))


import os
import sys
from io import BytesIO, IOBase
import math
import itertools
import bisect
import heapq

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')

def binary(n):
	return bin(n).replace('0b', '')

def decimal(s):
	return int(s, 2)

def pow2(n):
	p = 0
	while n > 1:
		n //= 2
		p += 1
	return 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(i)
			n = n / i
	if n > 2:
		l.append(int(n))
	return l

def isPrime(n):
	if n == 1:
		return False
	else:
		root = int(n ** 0.5)
		root += 1
		for i in range(2, root):
			if n % i == 0:
				return False
		return True

def maxPrimeFactors(n):
	maxPrime = -1
	while n % 2 == 0:
		maxPrime = 2
		n >>= 1
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			maxPrime = i
			n = n / i
	if n > 2:
		maxPrime = n
	return int(maxPrime)

def countcon(s, i):
	c = 0
	ch = s[i]
	for i in range(i, len(s)):
		if s[i] == ch:
			c += 1
		else:
			break
	return c

def lis(arr):
	n = len(arr)
	lis = [1] * n
	for i in range(1, n):
		for j in range(0, i):
			if arr[i] > arr[j] and lis[i] < lis[j] + 1:
				lis[i] = lis[j] + 1
	maximum = 0
	for i in range(n):
		maximum = max(maximum, lis[i])
	return maximum

def isSubSequence(str1, str2):
	m = len(str1)
	n = len(str2)
	j = 0
	i = 0
	while j < m and i < n:
		if str1[j] == str2[i]:
			j = j + 1
		i = i + 1
	return j == m

def maxfac(n):
	root = int(n ** 0.5)
	for i in range(2, root + 1):
		if n % i == 0:
			return n // i
	return n

def p2(n):
	c = 0
	while n % 2 == 0:
		n //= 2
		c += 1
	return c

def seive(n):
	primes = [True] * (n + 1)
	primes[1] = primes[0] = False
	for i in range(2, n + 1):
		if primes[i]:
			for j in range(i + i, n + 1, i):
				primes[j] = False
	p = []
	for i in range(0, n + 1):
		if primes[i]:
			p.append(i)
	return p

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 denofactinverse(n, m):
	fac = 1
	for i in range(1, n + 1):
		fac = fac * i % m
	return pow(fac, m - 2, m)

def numofact(n, m):
	fac = 1
	for i in range(1, n + 1):
		fac = fac * i % m
	return fac

def chk(n, d):
	if str(d) in str(n):
		return True
	return False

def dac(l, f, r, cd):
	if f + 1 == r:
		if l[f - 1] > l[r - 1]:
			ans[f] = cd
			ans[r - 1] = cd + 1
	if f == r:
		return
	else:
		ind = l.index(max(l[f:r]))
		ans[ind] = cd
		dac(l, f, ind, cd + 1)
		dac(l, ind + 1, r, cd + 1)
for xyz in range(0, int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	ans = [-1] * n
	if n == 1:
		ans = [0]
	else:
		dac(l, 0, n, 0)
	print(*ans)


def dfs(lists, cur, dep):
	if lists == []:
		return
	dict.update({cur: dep})
	dfs(lists[:lists.index(cur)], max(lists[:lists.index(cur)], default=0), dep + 1)
	dfs(lists[lists.index(cur) + 1:], max(lists[lists.index(cur) + 1:], default=0), dep + 1)
p = int(input())
for _ in range(p):
	dict = {}
	q = int(input())
	s = list(map(int, input().split()))
	dfs(s, max(s), 0)
	answer = []
	for i in s:
		answer.append(str(dict[i]))
	print(' '.join(answer))


def find_h(a, depth):
	if not a:
		return
	max_item = max(a)
	max_ind = a.index(max_item)
	d[max_item] = depth
	find_h(a[:max_ind], depth + 1)
	find_h(a[max_ind + 1:], depth + 1)
n = int(input())
for i in range(n):
	l = int(input())
	a = list(map(int, input().split()))
	d = {}
	find_h(a, 0)
	for i in a:
		print(d[i], end=' ')
	print()


def rec(l, r, a, ans, d):
	if l > r:
		return
	if l == r:
		ans[l] = d
		return
	ma = -1
	for j in range(l, r + 1):
		if a[j] > ma:
			ma = a[j]
			m = j
	ans[m] = d
	if l < m:
		rec(l, m - 1, a, ans, d + 1)
	if r > m:
		rec(m + 1, r, a, ans, d + 1)
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [0] * n
	rec(0, n - 1, a, ans, 0)
	for x in ans:
		print(x, end=' ')
	print()


import sys
from collections import deque
input_ = lambda : sys.stdin.readline().strip('\r\n')
ii = lambda : int(input_())
il = lambda : list(map(int, input_().split()))
ilf = lambda : list(map(float, input_().split()))
ip = lambda : input_()
fi = lambda : float(input_())
li = lambda : list(input_())
pr = lambda x: print(x)
f = lambda : sys.stdout.flush()

def gen(x, l, r):
	if l == r:
		return
	ind = -1
	val = -1
	for i in range(l, r):
		if val < a[i]:
			ind = i
			val = a[i]
	gen(x + 1, l, ind)
	gen(x + 1, ind + 1, r)
	a[ind] = x
for _ in range(ii()):
	n = ii()
	a = il()
	gen(0, 0, n)
	print(*a)


def myfun(li, indices, curr, start, end):
	if start < end:
		aa = li[start]
		a = start
		for i in range(start, end):
			if li[i] > aa:
				a = i
				aa = li[i]
		indices[a] = curr
		myfun(li, indices, curr + 1, start, a)
		myfun(li, indices, curr + 1, a + 1, end)
for _ in range(int(input())):
	n = int(input())
	l = [int(x) for x in input().split()]
	indices = [-1 for i in range(n)]
	myfun(l, indices, 0, 0, n)
	print(*indices)


def recursive(array, dic, depth):
	if len(array) == 0:
		return
	raiz = max(array)
	diccionario[raiz] = depth
	izq = False
	der = False
	index_raiz = array.index(raiz)
	l_izq = array[0:index_raiz]
	l_der = array[index_raiz + 1:]
	depth += 1
	if izq and der:
		return diccionario
	recursive(l_izq, diccionario, depth)
	recursive(l_der, diccionario, depth)
	return diccionario
t = int(input())
for _ in range(t):
	l = int(input())
	array = list(map(int, input().split()))
	diccionario = dict()
	depth = 0
	while len(diccionario) < l:
		dic = recursive(array, diccionario, depth)
		for e in array:
			print(dic[e], end=' ')
	print()


import sys

def solve(n, a):
	d = [0] * n

	def set_d_max(start, end, d_last):
		if start == end:
			return
		i_max = start
		for i in range(start + 1, end):
			if a[i] > a[i_max]:
				i_max = i
		d[i_max] = d_last
		set_d_max(start, i_max, d_last + 1)
		set_d_max(i_max + 1, end, d_last + 1)
	set_d_max(0, n, 0)
	return ' '.join(map(str, d))

def main():
	res = ''
	input = sys.stdin.readline
	print = sys.stdout.write
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		res += str(solve(n, a)) + '\n'
	print(res)
main()


class SegmentTree:

	def __init__(self, array, f=lambda x, y: x + y, inf=0):
		self.height = (len(array) - 1).bit_length()
		self.n = 2 ** self.height
		self.id = inf
		self.tree = [self.id] * (2 * self.n)
		self.f = f
		for i in range(len(array)):
			self.tree[self.n + i] = array[i]
		for i in range(self.n - 1, 0, -1):
			self.tree[i] = self.f(self.tree[2 * i], self.tree[2 * i + 1])

	def update(self, i, x):
		i += self.n
		self.tree[i] = x
		while i > 1:
			i //= 2
			self.tree[i] = self.f(self.tree[2 * i], self.tree[2 * i + 1])

	def query(self, l, r):
		l += self.n
		r += self.n
		(lf, rf) = (self.id, self.id)
		while l < r:
			if l & 1:
				lf = self.f(lf, self.tree[l])
				l += 1
			if r & 1:
				r -= 1
				rf = self.f(self.tree[r], rf)
			l //= 2
			r //= 2
		return self.f(lf, rf)

	def BinarySearch(self, l, r, f):
		if not f(self.query(l, r)):
			return r + 1
		l += self.n
		r += self.n
		while True:
			if f(self.tree[l]):
				if l >= self.n:
					return l - self.n + 1
				else:
					l *= 2
			elif l % 2 == 0:
				l += 1
			else:
				l = l // 2 + 1

	def display(self):
		for i in range(self.n, self.n * 2):
			print(self.tree[i], end=' ')
			while i % 2 == 0:
				i //= 2
				print(self.tree[i], end=' ')
			print()
import sys
input = sys.stdin.readline

def solve(a, x):
	if len(a) == 0:
		return
	if len(a) == 1:
		ans[a[0] - 1] = x
		return
	m = max(a)
	ans[m - 1] = x
	for i in range(len(a)):
		if a[i] == m:
			solve(a[:i], x + 1)
			solve(a[i + 1:], x + 1)
t = int(input())
ansss = []
while t:
	t -= 1
	n = int(input())
	a = list(map(int, input().split()))
	ans = [0] * n
	solve(a, 0)
	anss = []
	for i in a:
		anss.append(ans[i - 1])
	ansss.append(anss)
for i in ansss:
	print(*i)


from itertools import combinations, accumulate, groupby, count
from sys import stdout, stdin, setrecursionlimit
from io import BytesIO, IOBase
from collections import *
from random import *
from bisect import *
from string import *
from queue import *
from heapq import *
from math import *
from re import *
from os import *

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 = read(self._fd, max(fstat(self._fd).st_size, 8192))
			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 = read(self._fd, max(fstat(self._fd).st_size, 8192))
			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:
			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')
(stdin, stdout) = (IOWrapper(stdin), IOWrapper(stdout))

def fast():
	return stdin.readline().strip()

def zzz():
	return [int(i) for i in fast().split()]
(z, zz) = (fast, lambda : list(map(int, z().split())))
(szz, graph, mod, szzz) = (lambda : sorted(zz()), {}, 10 ** 9 + 7, lambda : sorted(zzz()))

def lcd(xnum1, xnum2):
	return xnum1 * xnum2 // gcd(xnum1, xnum2)

def output(answer, end='\n'):
	stdout.write(str(answer) + end)
dx = [-1, 1, 0, 0, 1, -1, 1, -1]
dy = [0, 0, 1, -1, 1, -1, -1, 1]
num = int(z())

def solve(l, r, d):
	if l > r:
		return
	if l == r:
		ans[l] = d
		return
	newArr = arr[l:r + 1]
	posMx = newArr.index(max(newArr)) + l
	ans[posMx] = d
	solve(l, posMx - 1, d + 1)
	solve(posMx + 1, r, d + 1)
for _ in range(num):
	n = int(z())
	arr = zzz()
	ans = [-1] * n
	solve(0, n - 1, 0)
	print(*ans)


import sys, collections, math, itertools, random, bisect
INF = sys.maxsize

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

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

def input():
	return sys.stdin.readline().strip()
mod = 1000000007
m = collections.defaultdict(int)

def mt(arr, left, n, curr):
	if left <= n and n >= 0:
		mx = -INF
		mxi = 0
		for i in range(left, n + 1):
			if arr[i] > mx:
				mx = arr[i]
				mxi = i
		mt(arr, left, mxi - 1, curr + 1)
		mt(arr, mxi + 1, n, curr + 1)
		m[arr[mxi]] = curr
for _ in range(int(input())):
	m = collections.defaultdict(int)
	n = int(input())
	arr = get_array()
	mxi = 0
	mx = -INF
	for i in range(n):
		if arr[i] > mx:
			mx = arr[i]
			mxi = i
	m[arr[mxi]] = 0
	mt(arr, 0, mxi - 1, 1)
	mt(arr, mxi + 1, n - 1, 1)
	for i in range(n):
		print(m[arr[i]], end=' ')
	print()


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [0] * n
	s = [(0, n, 0)]
	while s:
		(i_s, i_e, lv) = s.pop()
		max_d = max(a[i_s:i_e])
		max_i = a.index(max_d)
		ans[max_i] = lv
		if i_s < max_i:
			s.append((i_s, max_i, lv + 1))
		if max_i + 1 < i_e:
			s.append((max_i + 1, i_e, lv + 1))
	print(' '.join(map(str, ans)))


def tree(y, c):
	if not y:
		return
	m = max(y)
	ind = y.index(m)
	d[m] = c
	tree(y[:ind], c + 1)
	tree(y[ind + 1:], c + 1)
t = int(input())
for _ in range(t):
	n = int(input())
	ar = list(map(int, input().split()))
	d = dict()
	tree(ar, 0)
	for i in ar:
		print(d[i], end=' ')
	print()


def permutation_to_tree(arr, i, j, depth, depths):
	if i == j:
		depths[i] = depth
		return
	root_val = -1
	root_index = -1
	for k in range(i, j + 1):
		if arr[k] > root_val:
			root_val = arr[k]
			root_index = k
	depths[root_index] = depth
	if root_index - 1 - i >= 0:
		permutation_to_tree(arr, i, root_index - 1, depth + 1, depths)
	if j - (root_index + 1) >= 0:
		permutation_to_tree(arr, root_index + 1, j, depth + 1, depths)
t = int(input())
for _ in range(t):
	n = int(input())
	permutation = [int(x) for x in input().split(' ')]
	depths = [-1 for _ in range(n)]
	permutation_to_tree(permutation, 0, n - 1, 0, depths)
	print(' '.join([str(x) for x in depths]))


def subArray(source, arr, dept):
	res = []
	res1 = []
	res2 = []
	if len(arr) == 1:
		return [dept]
	index = arr.index(max(arr))
	arr1 = arr[0:index]
	arr2 = arr[index + 1:len(arr)]
	arr[index] = dept
	while True:
		if len(arr1) > 0:
			res1 = subArray(source, arr1, dept + 1)
		if len(arr2) > 0:
			res2 = subArray(source, arr2, dept + 1)
			break
		else:
			break
	res = res1 + [dept] + res2
	return res
n = int(input())
for i in range(0, n):
	m = int(input())
	arr = [int(x) for x in input().split()]
	print(str(subArray(arr, arr, 0))[1:-1].replace(', ', ' '))


import sys
import math
N = int(10000.0 + 5)
sys.setrecursionlimit(N)

def charming():
	n = int(input())
	a = [0] + list(map(int, input().split()))
	dep = [0] * (n + 1)

	def dfs(l, r, d):
		if l > r:
			return
		if l == r:
			dep[l] = d
			return
		mx = max(a[l:r + 1])
		mx_id = a[l:r + 1].index(mx) + l
		dep[mx_id] = d
		dfs(l, mx_id - 1, d + 1)
		dfs(mx_id + 1, r, d + 1)
	dfs(1, n, 0)
	for i in range(1, n + 1):
		print(dep[i], end=' ')
	print()
for t in range(int(input())):
	charming()


s = set()

def tree(l, r, a, d, cd=0):
	if r < l:
		return
	if l == r:
		d[l] = cd
	pos = l
	for i in range(l, r + 1):
		if a[i] > a[pos]:
			pos = i
	d[pos] = cd
	tree(l, pos - 1, a, d, cd + 1)
	tree(pos + 1, r, a, d, cd + 1)

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	d = [0] * n
	tree(0, n - 1, a, d)
	for i in d:
		print(i, end=' ')
	print()
t = int(input())
while t > 0:
	t -= 1
	solve()


depth = list()

def gen_depth(left, routedepth, right):
	if left > right:
		return 0
	route = left
	for i in range(left, right + 1):
		if arr[route] < arr[i]:
			route = i
	depth[route] = routedepth
	gen_depth(left, routedepth + 1, route - 1)
	gen_depth(route + 1, routedepth + 1, right)
tc = int(input())
for cs in range(tc):
	n = int(input())
	x = 0
	line = input()
	arr = list(map(int, line.split()))
	for i in range(n):
		depth.append(0)
	gen_depth(0, 0, n - 1)
	for i in range(n):
		print(depth[i], end=' ')
	print('')


def f(a, res, dep, idx):
	if len(a) == 0:
		return
	mx = max(a)
	res[idx[mx - 1]] = dep
	mi = a.index(mx)
	f(a[:mi], res, dep + 1, idx)
	f(a[mi + 1:], res, dep + 1, idx)

def solve(n, a):
	res = [0] * n
	idx = [0] * n
	for i in range(n):
		idx[a[i] - 1] = i
	f(a, res, 0, idx)
	return res
t = int(input())
ans = [0] * t
for i in range(t):
	n = int(input())
	a = [int(i) for i in input().split()]
	ans[i] = solve(n, a)
for i in ans:
	print(*i)


import sys
import math
t = int(input())

def cond(a, b):
	return max(a, b) / min(a, b)

def solve2(nums, n):
	ans = 0
	maxind = nums.index(max(nums))
	nind = nums.index(n)
	if nind == maxind:
		return ans
	elif nind > maxind:
		return 1 + solve2(nums[maxind + 1:], n)
	elif nind < maxind:
		return 1 + solve2(nums[0:maxind], n)

def solve(nums, n):
	ans = []
	for i in range(n):
		sys.stdout.write('' + str(solve2(nums, nums[i])) + ' ')
	sys.stdout.write('\n')
for i in range(t):
	n = int(input())
	numss = input().split()
	nums = [int(i) for i in numss]
	solve(nums, n)


def myfunction(a, start, end, depth, d):
	if start <= end:
		ind = -1
		m = 0
		for i in range(start, end + 1):
			if a[i] > m:
				ind = i
				m = a[i]
		if ind != -1:
			d[ind] = depth
		myfunction(a, start, ind - 1, depth + 1, d)
		myfunction(a, ind + 1, end, depth + 1, d)
for _ in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	d = [0] * n
	myfunction(a, 0, n - 1, 0, d)
	for i in d:
		print(i, end=' ')
	print('')


def solve(l, r, arr, d, cur=0):
	if l > r:
		return
	if l == r:
		d[l] = cur
	mx = l
	for i in range(l + 1, r + 1):
		if arr[mx] < arr[i]:
			mx = i
	d[mx] = cur
	solve(l, mx - 1, arr, d, cur + 1)
	solve(mx + 1, r, arr, d, cur + 1)
t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(s) for s in input().split(' ')]
	d = [0] * n
	solve(0, n - 1, arr, d)
	print(' '.join(map(str, d)))


def dfs(d, a):
	if len(a) == 1:
		return [d]
	elif len(a) == 0:
		return []
	i = a.index(max(a))
	return dfs(d + 1, a[:i]) + [d] + dfs(d + 1, a[i + 1:])
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	l = dfs(0, a)
	print(*l, sep=' ')


import math as m
i = input()
inp = []
for a in range(0, int(i)):
	input()
	inp.append([int(x) for x in input().split()])

def func(arr, depth):
	n = len(arr)
	if n == 1:
		return [depth]
	elif n == 0:
		return []
	m = arr[0]
	p = 0
	for i in range(1, len(arr)):
		if arr[i] > m:
			m = arr[i]
			p = i
	return func(arr[:p], depth + 1) + [depth] + func(arr[p + 1:], depth + 1)
for arr in inp:
	d = func(arr, 0)
	print(' '.join([str(x) for x in d]))


t = int(input())
for i in range(t):
	n = int(input())
	lst = list(map(int, input().split()))
	dic = {}
	for h in lst:
		dic[h] = -1

	def fun(left, right, ma, ht):
		if left == right:
			dic[ma] = ht
			return
		else:
			maxind = lst.index(ma)
			dic[ma] = ht
			if lst[left:maxind] != []:
				fun(left, maxind - 1, max(lst[left:maxind]), ht + 1)
			if lst[maxind + 1:right + 1] != []:
				fun(maxind + 1, right, max(lst[maxind + 1:right + 1]), ht + 1)
	fun(0, n - 1, max(lst), 0)
	lsta = []
	for j in dic.values():
		lsta.append(j)
	print(*lsta)


T = int(input())
for _ in range(T):
	N = int(input())
	sol = [-1 for _ in range(N)]
	numbers = list(map(int, input().split(' ')))

	def prueba(arr, depth=0, der=0):
		if not arr:
			return
		i = arr.index(max(arr))
		sol[der + i] = depth
		left = arr[:i]
		right = arr[i + 1:]
		prueba(left, depth + 1, der)
		prueba(right, depth + 1, der + i + 1)
	prueba(numbers)
	print(*sol)


T = int(input())
for t in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	l = [0 for i in range(n)]

	def f(a, low, high, count):
		i = a.index(max(a[low:high + 1]))
		l[i] = count
		if low != high:
			if i == low:
				f(a, low + 1, high, count + 1)
			elif i == high:
				f(a, low, high - 1, count + 1)
			else:
				f(a, low, i - 1, count + 1)
				f(a, i + 1, high, count + 1)
	f(a, 0, n - 1, 0)
	print(*l)


n_testes = int(input())
sequencias = []
for e in range(n_testes):
	qntd_elementos = int(input())
	sequencia = list(map(int, input().split()))
	sequencias.append(sequencia)

def retorna_maior(seq, inicio, fim):
	i_maior = inicio
	for i in range(inicio, fim + 1):
		if seq[i] > seq[i_maior]:
			i_maior = i
	return i_maior

def resolve(seq, inicio, fim, profundidade, resposta):
	if inicio > fim:
		return
	indice_maior = retorna_maior(seq, inicio, fim)
	resposta[indice_maior] = profundidade
	resolve(seq, inicio, indice_maior - 1, profundidade + 1, resposta)
	resolve(seq, indice_maior + 1, fim, profundidade + 1, resposta)
	return resposta
profundidades = []
for s in sequencias:
	profundidades.append(resolve(s, 0, len(s) - 1, 0, [0] * len(s)))
for p in profundidades:
	print(str(p)[1:-1].replace(',', ''))


response = {}

def get_sub_array(start, end, array):
	return array[start:end]

def build_tree(array, depth):
	if len(array) > 0:
		maximum = max(array)
		response[maximum]['depth'] = depth
		index = array.index(maximum)
		build_tree(get_sub_array(0, index, array), depth + 1)
		build_tree(get_sub_array(index + 1, len(array), array), depth + 1)

def print_result(array):
	result = ''
	for j in range(len(array)):
		result = result + str(response[array[j]]['depth'])
		if j < len(array) - 1:
			result = result + ' '
	print(result)
for _ in range(int(input())):
	n = int(input())
	numbers = list(map(int, input().split()))
	for i in range(len(numbers)):
		number = numbers[i]
		response[number] = {}
		response[number]['index'] = i
		response[number]['depth'] = 0
	build_tree(numbers, 0)
	print_result(numbers)


itype = int

def inp():
	return int(input())

def tinput():
	return list(map(itype, input().split(' ')))
cr = []

def solve(a, si):
	if a == []:
		return
	global cr
	root = a.index(max(a))
	for i in range(len(a)):
		if i != root:
			cr[i + si] += 1
	solve(a[:root], si)
	solve(a[root + 1:], root + 1 + si)
output = []
for tc in range(int(input())):
	n = inp()
	a = tinput()
	cr = [0] * n
	solve(a, 0)
	output.append(' '.join(list(map(str, cr))))
print('\n'.join(output))


ans = []

def rec(l1, l2, par):
	global ans
	if l1 != []:
		mx1 = max(l1)
		ans[mx1 - 1] = par + 1
		idx1 = l1.index(mx1)
		rec(l1[0:idx1], l1[idx1 + 1:], par + 1)
	if l2 != []:
		mx2 = max(l2)
		ans[mx2 - 1] = par + 1
		idx2 = l2.index(mx2)
		rec(l2[0:idx2], l2[idx2 + 1:], par + 1)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [0 for i in range(n)]
	mx = max(a)
	ans[mx - 1] = 0
	idx = a.index(mx)
	rec(a[0:idx], a[idx + 1:], 0)
	for i in a:
		print(ans[i - 1], end=' ')
	print()


import math, sys
from collections import defaultdict, Counter, deque
from bisect import bisect_left, bisect_right
INF = float('inf')
MOD = int(1000000000.0) + 7
MAX = int(1000000.0) + 1
ans = []

def dc(arr, l, r, depth):
	if r - l < 1:
		return
	m = arr.index(max(arr[l:r]), l, r)
	ans[m] = depth
	dc(arr, l, m, depth + 1)
	dc(arr, m + 1, r, depth + 1)

def solve():
	n = int(input())
	global ans
	ans = [0 for i in range(n)]
	arr = array()
	dc(arr, 0, n, 0)
	print(*ans)

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

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

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

def print(*args, sep=' ', end='\n'):
	first = True
	for arg in args:
		if not first:
			sys.stdout.write(sep)
		sys.stdout.write(str(arg))
		first = False
	sys.stdout.write(end)
primes = [1 for i in range(MAX)]

def sieve():
	global primes
	primes[0] = primes[1] = 0
	i = 2
	while i <= MAX ** 0.5:
		j = i * i
		while primes[i] and j < MAX:
			if j % i == 0:
				primes[j] = 0
			j += i
		i += 1

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

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


def build(v, count):
	if v == []:
		return
	maxi = 0
	for (ind, val) in enumerate(v):
		if v[ind] > v[maxi]:
			maxi = ind
	resp[v[maxi]] = count
	build(v[0:maxi], count + 1)
	build(v[maxi + 1:], count + 1)
e = int(input())
while e:
	e -= 1
	n = int(input())
	resp = [0] * (n + 1)
	lista = input()
	lista = list(map(int, lista.split()))
	build(lista, 0)
	for i in range(0, n):
		print(resp[lista[i]], end=' ')
	print()


import math
import sys

def inpu():
	return sys.stdin.readline().strip()
T = int(input())
n = 0

def use(ans, i):
	tb = -1
	for i in range(i + 1, n):
		if ans[i] != -1:
			tb = ans[i]
			break
	for i in range(i - 1, -1, -1):
		if ans[i] != -1:
			return max(tb, ans[i]) + 1
	return tb + 1
for t in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	d = False
	ans = [-1] * n
	r = sorted(range(n), key=lambda i: a[i])
	for i in range(n - 1, -1, -1):
		ans[r[i]] = use(ans, r[i])
	for i in ans:
		print(i, end=' ')
	print()


def foo(a, s, e, d, ans):
	if s == e:
		return
	max_a_i = 0
	max_idx = -1
	for i in range(s, e):
		if a[i] > max_a_i:
			max_a_i = a[i]
			max_idx = i
	ans[max_idx] = d
	foo(a, s, max_idx, d + 1, ans)
	foo(a, max_idx + 1, e, d + 1, ans)
for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	ans = [-1] * n
	foo(a, 0, n, 0, ans)
	print(' '.join([str(i) for i in ans]))


def get_depth(l, depth):
	if len(l) > 0:
		if len(l) > 1:
			ele = max(l)
			d[ele] = depth
			depth += 1
			loc = l.index(ele)
			l1 = l[:loc]
			try:
				l2 = l[loc + 1:]
			except:
				l2 = []
			get_depth(l1, depth)
			get_depth(l2, depth)
		else:
			d[l[0]] = depth
T = int(input())
for _ in range(0, T):
	n = int(input())
	a = list(map(int, input().split()))
	d = {i: 0 for i in a}
	get_depth(a, 0)
	print(*list(d.values()))


for _ in range(int(input())):
	n = int(input())
	lis = list(map(int, input().split()))
	output = [0] * len(lis)

	def recurse(low, high, d):
		max1 = -float('Inf')
		index = -1
		if low > high:
			return
		for i in range(low, high + 1):
			if lis[i] > max1:
				max1 = lis[i]
				index = i
		output[index] = d
		recurse(low, index - 1, d + 1)
		recurse(index + 1, high, d + 1)
	recurse(0, len(lis) - 1, 0)
	for i in output:
		print(i, end=' ')
	print()


import math
import collections
import random

def read_list() -> list:
	return [int(i) for i in input().strip().split()]

def read_num() -> int:
	return int(input().strip())

def find(arr: list, ans: list, level: int):
	if arr == []:
		return
	if len(arr) == 1:
		ans[arr[0]] = level
	idx = arr.index(max(arr))
	ans[arr[idx]] = level
	find(arr[:idx], ans, level + 1)
	find(arr[idx + 1:], ans, level + 1)
t = read_num()
for i in range(t):
	n = read_num()
	arr = read_list()
	ans = [0] * (n + 5)
	find(arr, ans, 0)
	for i in arr:
		print(ans[i], end=' ')
	print()


def calculation(length, values, x):
	if length == 0:
		return []
	if length == 1:
		return [x]
	maximum = values.index(max(values))
	first = values[:maximum]
	last = values[maximum + 1:]
	return calculation(len(first), first, x + 1) + [x] + calculation(len(last), last, x + 1)

def main():
	number = int(input())
	for i in range(number):
		cont = 0
		values = []
		length_permutation = int(input())
		input_values = input().split(' ')
		for i in input_values:
			values.append(int(i))
		result = calculation(length_permutation, values, cont)
		for i in range(len(result) - 1):
			print(result[i], end=' ')
		print(result[len(result) - 1])
main()


def dfs(l, r, arr, depth, dd):
	if l > r:
		return
	m = -float('inf')
	idx = 0
	for i in range(l, r + 1):
		if m < arr[i]:
			m = arr[i]
			idx = i
	d[m] = depth
	dfs(l, idx - 1, arr, depth + 1, d)
	dfs(idx + 1, r, arr, depth + 1, d)
T = int(input())
for _ in range(T):
	N = int(input())
	A = list(map(int, input().split()))
	d = {x: 0 for x in A}
	dfs(0, N - 1, A, 0, d)
	ans = []
	for i in range(N):
		ans.append(d[A[i]])
	print(*ans)


def verify(arr, i):
	if len(arr) == 1:
		return [i]
	if len(arr) == 0:
		return []
	pos = arr.index(max(arr))
	left = arr[:pos]
	right = arr[pos + 1:]
	return verify(left, i + 1) + [i] + verify(right, i + 1)
t = int(input())
for _ in range(t):
	n = int(input())
	lst = list(map(int, input().split()))
	perm = verify(lst, 0)
	for idx in perm:
		print(idx, end=' ')
	print()


import sys
input = sys.stdin.buffer.readline
ri = lambda : int(input())
rl = lambda : list(map(int, input().split()))
rs = lambda : input().decode().rstrip('\n\r')
wrt = sys.stdout.write
pr = lambda *args, end='\n': wrt(' '.join([str(x) for x in args]) + end)
xrange = lambda *args: reversed(range(*args))
cdiv = lambda x, y: -(-x // y)
enum = enumerate
inf = float('inf')
mod = 10 ** 9 + 7
from collections import defaultdict as dd, Counter
from queue import deque
from heapq import *
Testcase = ri()
for testcase in range(Testcase):
	(n,) = rl()
	a = rl()
	vis = [False for i in range(n)]
	k = max(a)
	q = deque()
	q.append([k, a.index(k), 0])
	ans = [0 for i in range(n)]
	while q:
		(k, i, d) = q.popleft()
		vis[i] = True
		ans[i] = d
		mx = 0
		ni = 0
		f = False
		for j in xrange(0, i):
			if vis[j]:
				break
			f = True
			if a[j] > mx:
				ni = j
				mx = a[j]
		if f:
			q.append([mx, ni, d + 1])
		mx = 0
		ni = 0
		f = False
		for j in range(i + 1, n):
			if vis[j]:
				break
			f = True
			if a[j] > mx:
				ni = j
				mx = a[j]
		if f:
			q.append([mx, ni, d + 1])
	print(*ans)


def build(l, r, depth):
	mxid = max(range(l, r + 1), key=lambda a: ls[a])
	if mxid > l:
		build(l, mxid - 1, depth + 1)
	if mxid < r:
		build(mxid + 1, r, depth + 1)
	d[mxid] = depth
for _ in range(int(input())):
	n = int(input())
	ls = list(map(int, input().split()))
	d = [0] * n
	build(0, n - 1, 0)
	print(' '.join(map(str, d)))


import sys
input = sys.stdin.readline
(inp, ip) = (lambda : int(input()), lambda : [int(w) for w in input().split()])
import sys
sys.setrecursionlimit(10 ** 5)

def func(l, r, dep):
	global n, x, d, idx
	if l > r:
		return
	if l == r:
		d[l] = dep
		return
	mx = max(x[l:r + 1])
	ind = idx[mx]
	d[ind] = dep
	func(l, ind - 1, dep + 1)
	func(ind + 1, r, dep + 1)
for _ in range(inp()):
	n = inp()
	x = ip()
	idx = [0] * (n + 1)
	for i in range(n):
		idx[x[i]] = i
	d = [0] * n
	ind = x.index(n)
	func(0, ind - 1, 1)
	func(ind + 1, n - 1, 1)
	print(*d)


def tree(arr, d):
	if not arr:
		return
	m = max(arr)
	mi = arr.index(m)
	ans[m] = d
	tree(arr[:mi], d + 1)
	tree(arr[mi + 1:], d + 1)
for case in range(int(input())):
	ans = {}
	n = int(input())
	arr = [int(i) for i in input().split(' ')]
	tree(arr, 0)
	for i in arr:
		print(ans[i], end=' ')
	print()


import sys
import threading

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

class Node:

	def __init__(self, val, left=None, right=None) -> None:
		self.val = val
		self.left = left
		self.right = right

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		perms = list(map(int, input().split()))

		def recur(left, right):
			if left > right:
				return None
			max_idx = -1
			max_val = 0
			for idx in range(left, right + 1):
				if perms[idx] > max_val:
					max_val = perms[idx]
					max_idx = idx
			cur = Node(perms[max_idx])
			cur.left = recur(left, max_idx - 1)
			cur.right = recur(max_idx + 1, right)
			return cur
		depths = [0] * (n + 1)

		def dfs(node, depth):
			if not node:
				return
			depths[node.val] = depth
			dfs(node.left, depth + 1)
			dfs(node.right, depth + 1)
		root = recur(0, n - 1)
		dfs(root, 0)
		ans = [0] * n
		for (idx, val) in enumerate(perms):
			ans[idx] = depths[val]
		print(*ans)
sys.setrecursionlimit(1 << 30)
threading.stack_size(1 << 27)
main_thread = threading.Thread(target=main)
main_thread.start()
main_thread.join()


def find_pos(l, r, height, ans):
	height += 1
	if l != []:
		ans[max(l) - 1] = height
		max_l = l.index(max(l))
		l_l = l[:max_l]
		r_l = l[max_l + 1:]
		find_pos(l_l, r_l, height, ans)
	if r != []:
		ans[max(r) - 1] = height
		max_r = r.index(max(r))
		l_r = r[:max_r]
		r_r = r[max_r + 1:]
		find_pos(l_r, r_r, height, ans)
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split(' ')))[:n]
	ans = [0 for _ in range(n)]
	max_a = a.index(max(a))
	l = a[:max_a]
	r = a[max_a + 1:]
	height = 0
	find_pos(l, r, height, ans)
	for i in range(n):
		a[i] = ans[a[i] - 1]
	print(' '.join(map(str, a)))


import sys
input = sys.stdin.readline

def get_max_index(a, left_index, right_index):
	mx = -1
	mx_index = None
	for index in range(left_index, right_index + 1):
		if a[index] > mx:
			mx = a[index]
			mx_index = index
	return mx_index

def solve(n, a):
	res = [-1] * n

	def rec_solve(left_index, right_index, depth):
		if left_index > right_index:
			return
		index = get_max_index(a, left_index, right_index)
		res[index] = depth
		rec_solve(left_index, index - 1, depth + 1)
		rec_solve(index + 1, right_index, depth + 1)
	rec_solve(0, n - 1, 0)
	return res
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	res = solve(n, a)
	print(*res)


t = int(input())

def helper(arr, start, end, memo, curr_depth):
	if start > end:
		return
	val = -1
	val_index = -1
	for (index, value) in enumerate(arr[start:end + 1]):
		if value > val:
			val = value
			val_index = index + start
	memo[val_index] = curr_depth
	helper(arr, start, val_index - 1, memo, curr_depth + 1)
	helper(arr, val_index + 1, end, memo, curr_depth + 1)
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	memo = [0] * n
	helper(arr, 0, n - 1, memo, 0)
	print(*memo)


from math import ceil, floor, log
import sys, threading
from heapq import heappush, heappop
from collections import Counter, defaultdict, deque
import bisect
input = lambda : sys.stdin.readline().strip()
c = lambda x: 10 ** 9 if x == '?' else int(x)

def rec(a, l, r, m, i, l1):
	if l == r:
		l1[l] = i
		return
	if l > r:
		return
	l1[max(m[l:r + 1], key=lambda x: a[x])] = i
	rec(a, l, max(m[l:r + 1], key=lambda x: a[x]) - 1, m, i + 1, l1)
	rec(a, max(m[l:r + 1], key=lambda x: a[x]) + 1, r, m, i + 1, l1)

class node:

	def __init__(self, x, y):
		self.a = [x, y]

	def __lt__(self, b):
		return b.a[0] < self.a[0]

	def __repr__(self):
		return str(self.a[0]) + ' ' + str(self.a[1])

def main():
	for _ in range(int(input())):
		n = int(input())
		a = list(map(int, input().split()))
		l = [0] * n
		rec(a, 0, n - 1, list(range(n)), 0, l)
		print(*l)
max_recur_size = 10 ** 3 * 2 + 1000
max_stack_size = max_recur_size * 500
sys.setrecursionlimit(max_recur_size)
threading.stack_size(max_stack_size)
thread = threading.Thread(target=main)
thread.start()


result = []
cases = int(input())
templi = [0] * 100

def getSeq(li, dep, start, end):
	if start >= end:
		return
	x = li.index(max(li[start:end]))
	templi[x] = dep
	if x > 0:
		getSeq(li, dep + 1, start, x)
	if x + 1 < len(li):
		getSeq(li, dep + 1, x + 1, end)
for i in range(cases):
	num = int(input())
	ain = list(map(int, input().split(' ')))
	getSeq(ain, 0, 0, len(ain))
	result.append(' '.join((str(s) for s in templi[:len(ain)])))
	templi = [0] * 100
for _ in result:
	print(_)


def build(l, r, depth):
	mxid = l
	for i in range(l, r + 1):
		if ls[i] > ls[mxid]:
			mxid = i
	if mxid > l:
		build(l, mxid - 1, depth + 1)
	if mxid < r:
		build(mxid + 1, r, depth + 1)
	d[mxid] = depth
for _ in range(int(input())):
	n = int(input())
	ls = list(map(int, input().split()))
	d = [0] * n
	build(0, n - 1, 0)
	print(' '.join(map(str, d)))


from sys import stdin, stdout
input = stdin.readline
from random import sample
t = int(input())
from collections import Counter
from math import sqrt, ceil

def f(arr, i, j, d, dist):
	if i == j:
		return
	nn = max(arr[i:j])
	for tl in range(i, j):
		if arr[tl] == nn:
			dist[tl] = d
			f(arr, i, tl, d + 1, dist)
			f(arr, tl + 1, j, d + 1, dist)

def ps(n):
	cp = 0
	while n % 2 == 0:
		n = n // 2
		cp += 1
	for ps in range(3, ceil(sqrt(n)) + 1, 2):
		while n % ps == 0:
			n = n // ps
			cp += 1
	if n != 1:
		return False
	return True

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

def factorials(n, r):
	slr = n
	dpr = r
	qrr = 1
	qs = 1
	mod = 10 ** 9 + 7
	for ip in range(slr - dpr + 1, slr + 1):
		qlr = qlr * ip % mod
	for ij in range(1, dpr + 1):
		qs = qs * ip % mod
	ans = qlr * modInverse(qs) % mod
	return ans

def modInverse(b):
	qr = 10 ** 9 + 7
	return pow(b, qr - 2, qr)
tt = [xa ** 3 for xa in range(0, 10 ** 4 + 1)]
qq = set(tt)
for jj in range(t):
	ll = int(input())
	n = ll
	arr = [int(x) for x in input().strip().split()]
	dist = [0] * n
	f(arr, 0, n, 0, dist)
	dist = [str(xa) for xa in dist]
	print(' '.join(dist))


def f(d, i, j):
	if i < j:
		k = a.index(max(a[i:j]), i, j)
		r[k] = d
		d += 1
		f(d, i, k)
		f(d, k + 1, j)
for s in [*open(0)][2::2]:
	a = (*map(int, s.split()),)
	n = len(a)
	r = [0] * n
	f(0, 0, n)
	print(*r)


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

def ans(a, d, c):
	if a:
		c += 1
		t = max(a)
		i = a.index(t)
		d[t] = c
		ans(a[:i], d, c)
		ans(a[i + 1:], d, c)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	d = dict()
	ans(a, d, -1)
	for i in a:
		print(d[i], end=' ')
	print()


t = int(input())

def solve(i, j, tree, ans, prof=0):
	if i > j:
		return
	maxi = i
	for z in range(i, j + 1):
		maxi = maxi if tree[maxi] > tree[z] else z
	ans[maxi] = prof
	solve(i, maxi - 1, tree, ans, prof + 1)
	solve(maxi + 1, j, tree, ans, prof + 1)
for x in range(t):
	n = int(input())
	tree = list(map(int, input().split()))
	ans = [0 for k in range(n)]
	solve(0, n - 1, tree, ans)
	print(' '.join(map(str, ans)))


def solve(l, r, d, arr, depth, ans):
	if l > r:
		return
	mx = max(arr[l:r + 1])
	ind = d[mx]
	ans[ind] = depth
	solve(ind + 1, r, d, arr, depth + 1, ans)
	solve(l, ind - 1, d, arr, depth + 1, ans)
	return ans
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	d = dict()
	for i in range(n):
		d[arr[i]] = i
	depth = 0
	ans = [0 for i in range(n)]
	ans = solve(0, n - 1, d, arr, depth, ans)
	print(*ans)


def searchIndexRoot(array, p, r):
	index = 0
	root = 0
	for i in range(p, r + 1):
		if array[i] > root:
			root = array[i]
			index = i
	return index

def calcDeph(array, p, r, deph):
	deph += 1
	if p <= r:
		index = searchIndexRoot(array, p, r)
		calcDeph(array, p, index - 1, deph)
		calcDeph(array, index + 1, r, deph)
		array[index] = deph
	return array

def formatResult(array):
	lengthArray = len(array)
	result = ''
	for i in range(lengthArray):
		if i < lengthArray:
			result += str(array[i]) + ' '
		else:
			result += str(array[i])
	return result
tests = int(input())
for i in range(tests):
	permutationLength = int(input())
	array = list(map(int, input().split()))
	result = calcDeph(array, 0, permutationLength - 1, -1)
	print(formatResult(result))


from math import *
from sys import *
from bisect import *
from collections import *
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	d = {}

	def fun(low, high, k):
		if low > high:
			return
		mx = 0
		j = 0
		for i in range(low, high + 1):
			if mx < a[i]:
				j = i
				mx = a[i]
		d[mx] = k
		fun(low, j - 1, k + 1)
		fun(j + 1, high, k + 1)
	fun(0, n - 1, 0)
	ans = []
	for i in range(n):
		ans.append(d[a[i]])
	print(*ans)


def dfs(l, r, d):
	if l >= r:
		return
	number = -1
	index = l
	for i in range(l, r):
		if a[i] > number:
			index = i
			number = a[i]
	t[index] = d
	dfs(l, index, d + 1)
	dfs(index + 1, r, d + 1)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	t = [0] * n
	dfs(0, n, 0)
	for i in t:
		print(i, end=' ')
	print()


import sys

def find_max_element_index(array_elements, min_index, max_index):
	max_value = array_elements[min_index]
	max_value_index = min_index
	for i in range(min_index + 1, max_index + 1):
		if array_elements[i] > max_value:
			max_value = array_elements[i]
			max_value_index = i
	return max_value_index

def find_depths(array_elements, min_index, max_index, level_now, level_dict):
	if max_index < min_index:
		return
	max_element_index = find_max_element_index(array_elements, min_index, max_index)
	level_dict[array_elements[max_element_index]] = level_now
	find_depths(array_elements, min_index, max_element_index - 1, level_now + 1, level_dict)
	find_depths(array_elements, max_element_index + 1, max_index, level_now + 1, level_dict)
inputlines = sys.stdin.readlines()
number_of_testcases = int(inputlines[0])
for i in range(number_of_testcases):
	number_of_elements = int(inputlines[2 * i + 1])
	array_elements = list(map(int, inputlines[2 * i + 2].split(' ')))
	level_dict = {}
	find_depths(array_elements, 0, number_of_elements - 1, 0, level_dict)
	for i in array_elements:
		print(level_dict[i], end=' ')
	print('')


def func(l, d, x):
	if len(l) == 1:
		d[l[0]] = x
		return d
	temp = l.index(max(l))
	d[max(l)] = x
	if temp > 0:
		d = func(l[:temp], d, x + 1)
	if temp < len(l) - 1:
		d = func(l[temp + 1:], d, x + 1)
	return d
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	d = func(l, {}, 0)
	x = []
	for i in l:
		x.append(d[i])
	print(*x)


def s():
	n = int(input())
	a = [int(it) for it in input().split()]
	h = [0] * (n + 1)

	def f(hi, x):
		if len(x) == 1:
			h[x[0]] = hi
			return
		maxi = x.index(max(x))
		h[x[maxi]] = hi
		if maxi > 0:
			f(hi + 1, x[0:maxi])
		if maxi < len(x) - 1:
			f(hi + 1, x[maxi + 1:])
	f(0, a)
	for it in a:
		print(h[it], end=' ')
	print()
k = int(input())
for i in range(k):
	s()


def buildTree(array, lvl):
	if len(array) == 1:
		return str(lvl)
	elif len(array) == 0:
		return ''
	depths = str(lvl)
	maxi = 0
	max = 0
	for i in range(len(array)):
		if array[i] > max:
			max = array[i]
			maxi = i
	lvl += 1
	depths = ' ' * (array[:maxi] != []) + depths + ' ' * (array[maxi + 1:] != [])
	depths = buildTree(array[:maxi], lvl) + depths + buildTree(array[maxi + 1:], lvl)
	return depths
t = int(input())
out = []
for i in range(t):
	n = input()
	s = list(map(int, input().split()))
	out.append(buildTree(s, 0))
for j in out:
	print(j)


import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')
inp = lambda : list(map(int, sys.stdin.readline().rstrip('\r\n').split()))
mod = 10 ** 9 + 7
Mod = 998244353
INF = float('inf')
tc = 1
(tc,) = inp()
for _ in range(tc):
	(n,) = inp()
	a = inp()

	class Node:

		def __init__(self, val):
			self.val = val
			self.left = None
			self.right = None

	def solve(i, j):
		if i >= j:
			return None
		Max = max(a[i:j])
		index = a.index(Max)
		root = Node(Max)
		root.left = solve(i, index)
		root.right = solve(index + 1, j)
		return root
	root = solve(0, n)
	d = {}
	ans = [0] * n
	for i in range(n):
		d[a[i]] = i

	def sol(node, lev):
		ans[d[node.val]] = lev
		if node.right:
			sol(node.right, lev + 1)
		if node.left:
			sol(node.left, lev + 1)
	sol(root, 0)
	print(*ans)


def divider(arr, level):
	if len(arr):
		max_val = max(arr)
		max_index = arr.index(max_val)
		left_arr = arr[:max_index]
		right_arr = arr[max_index + 1:]
		return [(max_val, level), *divider(left_arr, level + 1), *divider(right_arr, level + 1)]
	else:
		return []
in_length = int(input())
final_ouput = []
for i in range(in_length):
	length = input()
	inputs = [int(el) for el in input().split()]
	outputs = inputs[:]
	has_subdivisions = True
	original_level = 0
	mid_ans = divider(inputs, original_level)
	for (j, inp) in enumerate(inputs):
		num = mid_ans[j][0]
		idx = inputs.index(num)
		outputs[idx] = str(mid_ans[j][1])
	final_ouput.append(' '.join(outputs))
for out in final_ouput:
	print(out)


for _ in range(int(input())):
	n = int(input())
	arr = [int(num) for num in input().split()]
	num_dict = {}

	def merge(arr, l, r, n):
		global num_dict
		if l >= r:
			return
		M = max(arr[l:r])
		num_dict[M] = n
		k = arr.index(M)
		merge(arr, l, k, n + 1)
		merge(arr, k + 1, r, n + 1)
	merge(arr, 0, len(arr), 0)
	for num in arr:
		print(num_dict[num], end=' ')
	else:
		print()


def permuta(array, custo, mapa):
	if len(array) == 0:
		return
	max_indice = -1
	max_valor = -1
	for (indice, valor) in enumerate(array):
		if int(valor) > max_valor:
			max_indice = indice
			max_valor = int(valor)
	mapa[max_valor] = custo
	permuta(array[:max_indice], custo + 1, mapa)
	if max_indice != len(array) - 1:
		permuta(array[max_indice + 1:], custo + 1, mapa)

def resolve_arvore(array):
	mapa = {}
	permuta(array, 0, mapa)
	for i in array:
		print(mapa[int(i)])
	print('', end='\n')
entrada = int(input())
for i in range(entrada):
	valor = input()
	array = input().rstrip().split()
	resolve_arvore(array)


import sys

def argmax(A):
	idx = -1
	my_max = -1
	for i in range(len(A)):
		if A[i] > my_max:
			my_max = A[i]
			idx = i
	return idx

def solve(N, A):
	used_idxes = []
	ered = ['x'] * len(A)
	idx = argmax(A)
	used_idxes.append(idx)
	ered[idx] = 0
	max_value = 0
	while len(used_idxes) < N:
		used_idxes_copy = [i for i in used_idxes]
		if used_idxes_copy[0] > 0:
			arr1 = A[:used_idxes_copy[0]]
			if len(arr1) > 0:
				idx = argmax(arr1)
				ered[idx] = max_value + 1
				used_idxes.append(idx)
		if used_idxes[-1] < N - 1:
			arr2 = A[used_idxes_copy[-1] + 1:]
			if len(arr2) > 0:
				idx = argmax(arr2)
				ered[used_idxes_copy[-1] + idx + 1] = max_value + 1
				used_idxes.append(used_idxes_copy[-1] + idx + 1)
		for i in range(len(used_idxes_copy) - 1):
			arr3 = A[used_idxes_copy[i] + 1:used_idxes_copy[i + 1]]
			if len(arr3) > 0:
				idx = argmax(arr3)
				ered[used_idxes_copy[i] + idx + 1] = max_value + 1
				used_idxes.append(used_idxes_copy[i] + idx + 1)
		max_value += 1
		used_idxes = sorted(used_idxes)
	return ' '.join([str(e) for e in ered])

def run():
	out = ''
	T = int(input())
	for i in range(T):
		N = int(input())
		A = [int(x) for x in input().split()]
		print(solve(N, A))
run()


def helper(a, level=0, d={}):
	if a:
		maxi = max(a)
		i = a.index(maxi)
		d[maxi] = level
		helper(a[:i], level + 1, d)
		helper(a[i + 1:], level + 1, d)
	return d
for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	d = helper(a, 0, {})
	for i in a:
		print(d[i], end=' ')
	print(end='\n')


def find_depth(left, right, depth):
	if left > right:
		return
	max_index = left
	max_val = dp[left]
	for i in range(left, right + 1):
		if a[i] > max_val:
			max_val = a[i]
			max_index = i
	dp[max_index] = depth
	find_depth(left, max_index - 1, depth + 1)
	find_depth(max_index + 1, right, depth + 1)
t = int(input())
for tc in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	dp = [-1] * n
	find_depth(0, n - 1, 0)
	print(*dp, sep=' ')


import sys

def dfs(array, cnt):
	if len(array) == 1:
		idx = a.index(array[0])
		depth[idx] = cnt
		return
	value = max(array)
	depth_idx = a.index(value)
	depth[depth_idx] = cnt
	idx = array.index(value)
	left = array[:idx]
	right = array[idx + 1:]
	if len(left) > 0:
		dfs(left, cnt + 1)
	if len(right) > 0:
		dfs(right, cnt + 1)
t = int(sys.stdin.readline())
for i in range(t):
	n = int(sys.stdin.readline())
	a = list(map(int, sys.stdin.readline().split()))
	depth = [-1] * len(a)
	dfs(a, 0)
	for item in depth:
		print(item, end=' ')


def find_depth(numbers, depth):
	if len(numbers) == 0:
		return []
	max_n_index = 0
	for index in range(len(numbers)):
		if numbers[index] == max(numbers):
			max_n_index = index
			break
	numbers[max_n_index] = depth
	depth += 1
	return find_depth(numbers[:max_n_index], depth) + [numbers[max_n_index]] + find_depth(numbers[max_n_index + 1:], depth)
tc = int(input())
while tc:
	n = int(input())
	numbers = list(map(int, input().split()))
	print(*find_depth(numbers, 0))
	tc -= 1


def find_max_i(a, s, e):
	m = s
	for i in range(s, e):
		if a[i] > a[m]:
			m = i
	return m

def fill_d(a, r, s, e, d):
	if s >= e:
		return
	r1 = find_max_i(a, s, e)
	d[r1] = d[r] + 1
	fill_d(a, r1, s, r1, d)
	fill_d(a, r1, r1 + 1, e, d)
t = int(input())
ans = []
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	d = [0] * n
	fill_d(a, find_max_i(a, 0, n), 0, n, d)
	ans.append(d)
for i in ans:
	for j in i:
		print(j - 1, end=' ')
	print()


def tree(l, r, depth):
	if l > r:
		return
	m = max(a[l:r + 1])
	mi = a.index(m)
	d[mi] = depth
	tree(l, mi - 1, depth + 1)
	tree(mi + 1, r, depth + 1)
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	d = [0] * n
	tree(0, n - 1, 0)
	print(*d, sep=' ')


def aux(element_j, element_k, array_elements, element_c):
	if element_j == element_k:
		result[element_j] = element_c
		return
	indexBiggest = element_j
	for index in range(element_j, element_k + 1):
		if array_elements[index] > array_elements[indexBiggest]:
			indexBiggest = index
	result[indexBiggest] = element_c
	element_c += 1
	if element_j <= indexBiggest - 1:
		aux(element_j, indexBiggest - 1, array_elements, element_c)
	if element_k >= indexBiggest + 1:
		aux(indexBiggest + 1, element_k, array_elements, element_c)
for index in range(int(input())):
	input_n = int(input())
	input_a = list(map(int, input().split()))
	result = [0 for i in range(input_n)]
	aux(0, input_n - 1, input_a, 0)
	print(*result)


from collections import defaultdict
ddict = defaultdict(int)

def rec(arr, deeps):
	if len(arr) == 0:
		return
	if len(arr) == 1:
		ddict[arr[0]] = deeps
		return None
	max_ind = arr.index(max(arr))
	ddict[arr[max_ind]] = deeps
	rec(arr[:max_ind], deeps + 1)
	rec(arr[max_ind + 1:], deeps + 1)

def solve():
	n = int(input())
	a = [int(x) for x in input().split()]
	if len(a) == 1:
		return [0]
	rec(a, 0)
	return [ddict[elem] for elem in a]
t = int(input())
for _ in range(t):
	res = [str(x) for x in solve()]
	print(' '.join(res))


def func(l, r, x):
	global a
	global level
	if l < r:
		inde = -1
		for i in range(l, r + 1):
			if a[i] != x:
				level[i] += 1
			else:
				inde = i
		if inde == l:
			func(l + 1, r, max(a[l + 1:r + 1]))
		elif inde == r:
			func(l, r - 1, max(a[l:r]))
		else:
			x1 = max(a[l:inde])
			x2 = max(a[inde + 1:r + 1])
			func(l, inde - 1, x1)
			func(inde + 1, r, x2)
for w in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	level = [0] * n
	m = max(a)
	func(0, n - 1, m)
	for i in range(n):
		print(level[i], end=' ')
	print()


import sys
sys.setrecursionlimit(10 ** 9)
for _ in range(int(input())):

	def dfs(ii):
		lmi = lmv = -1
		for i in range(ii - 1, -1, -1):
			if b[i] != -1:
				break
			if a[i] > lmv:
				lmv = a[i]
				lmi = i
		if lmi != -1:
			b[lmi] = b[ii] + 1
			dfs(lmi)
		rmi = rmv = -1
		for i in range(ii + 1, n):
			if b[i] != -1:
				break
			if a[i] > rmv:
				rmv = a[i]
				rmi = i
		if rmi != -1:
			b[rmi] = b[ii] + 1
			dfs(rmi)
	n = int(input())
	a = list(map(int, input().split()))
	b = [-1] * n
	mv = mi = 0
	for i in range(n):
		if a[i] > mv:
			mv = a[i]
			mi = i
	b[mi] = 0
	dfs(mi)
	print(*b)


def solve(arr, level=0):
	if len(arr) == 0:
		return
	m = max(arr)
	i = a.index(m)
	out[i] = level
	x = arr.index(m)
	solve(arr[0:x], level + 1)
	solve(arr[x + 1:], level + 1)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	out = [-1 for i in range(n)]
	b = list(a)
	solve(b)
	print(*out)


from math import *
data = {}

def builder(w, l=0, d=None):
	if not w:
		return
	mx = max(w)
	ind = w.index(mx)
	left = w[:ind]
	right = w[ind + 1:]
	data[mx] = l
	builder(left, l + 1)
	builder(right, l + 1)

def solve():
	global data
	n = int(input())
	a = tuple(map(int, input().split()))
	builder(a)
	for item in a:
		print(data[item], end=' ')
	print()
	data = {}

def s():
	for _ in range(int(input())):
		solve()
s()


import sys
input = sys.stdin.readline

def main():
	t = int(input())
	for _ in range(t):
		N = int(input())
		A = [int(x) for x in input().split()]
		ans = [-1] * N

		def solve(l, r, depth):
			if l == r:
				ans[l] = depth
				return
			ma = 0
			mai = 0
			for i in range(l, r + 1):
				if A[i] > ma:
					mai = i
					ma = A[i]
			ans[mai] = depth
			if l != mai:
				solve(l, mai - 1, depth + 1)
			if r != mai:
				solve(mai + 1, r, depth + 1)
		solve(0, N - 1, 0)
		print(*ans)
main()


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	d = [0] * n

	def solve(w, c):
		if w:
			x = max(w)
			i = w.index(x)
			d[a.index(x)] = c
			solve(w[i + 1:], c + 1)
			solve(w[:i], c + 1)
	solve(a, 0)
	print(' '.join(map(str, d)))


testcases = int(input())

def depth_function(input_list, depth_list, current_depth, index_left, index_right):
	if index_left == index_right:
		return None
	max_sublist = max(input_list[index_left:index_right])
	max_index = input_list.index(max_sublist)
	depth_list[max_index] = current_depth
	depth_function(input_list, depth_list, current_depth + 1, index_left, max_index)
	depth_function(input_list, depth_list, current_depth + 1, max_index + 1, index_right)
for i in range(testcases):
	n = int(input())
	input_2 = input().split()
	permutation = list(map(int, input_2))
	depths = [0] * n
	depth_function(permutation, depths, 0, 0, n)
	print(' '.join(map(str, depths)))


def buidTree(arr, lvl):
	if len(arr) <= 0:
		return
	index = arr.index(max(arr))
	ans[arr[index]] += lvl
	buidTree(arr[:index], lvl + 1)
	buidTree(arr[index + 1:], lvl + 1)
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().strip().split()))
	ans = {}
	for key in arr:
		ans[key] = 0
	buidTree(arr, 0)
	print(*ans.values())


import sys
YES = 'YES'
NO = 'NO'
MOD = 1000000007

def input_int():
	return int(input())

def input_list():
	return input().split(' ')

def input_list_int():
	return list(map(int, input_list()))

def find_h(l, r, a, cur, h):
	if l >= r:
		return
	me = a[l]
	mi = l
	for i in range(l, r):
		if me < a[i]:
			me = a[i]
			mi = i
	h[mi] = cur
	find_h(l, mi, a, cur + 1, h)
	find_h(mi + 1, r, a, cur + 1, h)

def solve():
	n = input_int()
	a = input_list_int()
	h = [-1] * n
	find_h(0, n, a, 0, h)
	for i in range(0, n):
		print(h[i], end=' ')
	print()
query_count = input_int()
while query_count:
	query_count -= 1
	solve()


import sys

class Node:

	def __init__(self, val):
		self.val = val
		self.left = None
		self.right = None

def build(arr, dic):
	if len(arr) == 0:
		return
	tmp = max(arr)
	root = Node(tmp)
	idx = arr.index(tmp)
	root.left = build(arr[:idx], dic)
	root.right = build(arr[idx + 1:], dic)
	return root
for _ in range(int(input())):
	n = int(input())
	arrr = list(map(int, input().split()))
	dic = {}
	root = build(arrr, dic)
	dic = {}
	q = [root]
	l = 0
	arr = [root.val]
	while q:
		curr = q[0]
		if len(q) == len(arr):
			for i in arr:
				dic[i] = l
			l += 1
			arr = []
		if curr.left:
			q.append(curr.left)
			arr.append(curr.left.val)
		if curr.right:
			q.append(curr.right)
			arr.append(curr.right.val)
		q.pop(0)
	for i in range(n):
		arrr[i] = dic[arrr[i]]
	print(*arrr)


graph = {}

def solve(x):
	if not x:
		return 0
	root = max(x)
	i = x.index(root)
	left = solve(x[:i])
	right = solve(x[i + 1:])
	graph[root] = [left, right]
	return root

def dfs(graph, node, visited=None, h=0, depth=None):
	if visited == None:
		visited = set()
		depth = {}
	visited.add(node)
	depth[node] = h
	for n in set(graph[node]) - visited:
		if n == 0:
			continue
		dfs(graph, n, visited, h + 1, depth)
	return depth

def aff(x, depth):
	for a in x:
		print(depth[a], end=' ')
t = int(input())
for _ in range(t):
	n = int(input())
	x = list(map(int, input().split()))
	solve(x)
	depth = dfs(graph, max(x))
	aff(x, depth)
	print('')


import sys
sys.setrecursionlimit(10 ** 6)

def make(arr, depths, d, indices):
	if not arr:
		return
	index = arr.index(max(arr))
	depths[indices[arr[index]]] = str(d)
	make(arr[:index], depths, d + 1, indices)
	make(arr[index + 1:], depths, d + 1, indices)

def solve(n, arr, ans):
	depths = [0] * n
	indices = {}
	for i in range(n):
		indices[arr[i]] = i
	make(arr, depths, 0, indices)
	ans.append(' '.join(depths))

def main():
	t = int(input())
	ans = []
	for i in range(t):
		n = int(input())
		arr = list(map(int, input().split()))
		solve(n, arr, ans)
	print('\n'.join(ans))
main()


def depthofvertex(array, level, d):
	if not array:
		return
	maximum = max(array)
	d[maximum] = level
	index = array.index(maximum)
	depthofvertex(array[:index], level + 1, d)
	depthofvertex(array[index + 1:], level + 1, d)
for _ in range(int(input())):
	n = int(input())
	array = [int(x) for x in input().split()]
	d = dict()
	depthofvertex(array, 0, d)
	for element in array:
		print(d[element], end=' ')
	print()


import sys
from collections import defaultdict as dd
from math import *
from bisect import *

def sinp():
	return input()

def inp():
	return int(input())

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

def linp():
	return list(minp())

def strl():
	return list(input())

def pr(x):
	print(x)
mod = int(1000000000.0 + 7)

class newNode:

	def __init__(self, data):
		self.data = data
		self.left = None
		self.right = None

def buildTree(inorder, start, end):
	if start > end:
		return None
	i = Max(inorder, start, end)
	root = newNode(inorder[i])
	if start == end:
		return root
	root.left = buildTree(inorder, start, i - 1)
	root.right = buildTree(inorder, i + 1, end)
	return root

def Max(arr, strt, end):
	(i, Max) = (0, arr[strt])
	maxind = strt
	for i in range(strt + 1, end + 1):
		if arr[i] > Max:
			Max = arr[i]
			maxind = i
	return maxind

def printInorder(node):
	if node == None:
		return
	printInorder(node.left)
	print(node.data, end=' ')
	printInorder(node.right)

def getLevelUtil(node, data, level):
	if node == None:
		return 0
	if node.data == data:
		return level
	downlevel = getLevelUtil(node.left, data, level + 1)
	if downlevel != 0:
		return downlevel
	downlevel = getLevelUtil(node.right, data, level + 1)
	return downlevel

def getLevel(node, data):
	return getLevelUtil(node, data, 1)
for _ in range(inp()):
	n = inp()
	a = linp()
	root = buildTree(a, 0, n - 1)
	l = [0 for i in range(n)]
	d = dd(int)
	for i in range(1, n + 1):
		level = getLevel(root, i)
		d[i] = level - 1
	for i in range(n):
		l[i] = d[a[i]]
	print(*l)


import sys
from collections import *
import math
import bisect
sys.setrecursionlimit(10 ** 9)

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

def rec(l, arr):
	if len(arr) == 0:
		return
	ind = arr.index(max(arr))
	lev[dic[max(arr)]] = l
	rec(l + 1, arr[:ind])
	rec(l + 1, arr[ind + 1:])
	return
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	dic = {}
	for i in range(n):
		dic[a[i]] = i
	lev = [-1 for _ in range(n)]
	rec(0, a)
	print(*lev)


x = int(input())

def locate(arr, f, e, n):
	max = f
	if f == e:
		arr[f] = n
		return
	if f > e:
		return
	for i in range(f, e + 1):
		if arr[i] > arr[max]:
			max = i
	arr[max] = n
	locate(arr, f, max - 1, n + 1)
	locate(arr, max + 1, e, n + 1)
while x:
	n = int(input())
	num = list(map(int, input().split()))
	locate(num, 0, n - 1, 0)
	print(*num)
	x -= 1


def find_max(arr, from_index, to_index):
	max_v = arr[from_index]
	index_v = from_index
	for i in range(from_index, to_index + 1):
		if arr[i] > max_v:
			index_v = i
			max_v = arr[i]
	return index_v

def solve_depth(arr, d_arr, left, right, d):
	if left == right:
		d_arr[left] = d
	elif left < right:
		index = find_max(arr, left, right)
		solve_depth(arr, d_arr, left, index - 1, d + 1)
		solve_depth(arr, d_arr, index + 1, right, d + 1)
		d_arr[index] = d

def main():
	t = int(input())
	for i in range(t):
		n = int(input())
		line = input().split()
		arr = []
		d_arr = []
		for x in line:
			arr.append(int(x))
			d_arr.append(0)
		solve_depth(arr, d_arr, 0, n - 1, 0)
		for i in range(n):
			print(str(d_arr[i]), end=' ')
		print(' ')
main()


def f(l, r, d):
	if l >= r:
		return
	m = -1
	ind = l
	for i in range(l, r):
		if a[i] > m:
			ind = i
			m = a[i]
	t[ind] = d
	f(l, ind, d + 1)
	f(ind + 1, r, d + 1)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	t = [0] * n
	f(0, n, 0)
	for i in t:
		print(i, end=' ')
	print()


def permutationTransformation(array, i, j, blank, p):
	if j - i < 0:
		return
	mi = i
	for x in range(i, j + 1):
		if array[x] > array[mi]:
			mi = x
	blank[mi] = p
	permutationTransformation(array, i, mi - 1, blank, p + 1)
	permutationTransformation(array, mi + 1, j, blank, p + 1)
t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	blank = [0] * n
	permutationTransformation(l, 0, n - 1, blank, 0)
	for x in blank:
		print(x, end=' ')
	print()


def depth_perm(tree, level):
	if len(tree) == 0:
		return []
	else:
		max_elem = max(tree)
		i = tree.index(max_elem)
		half1 = tree[:i]
		half2 = tree[i + 1:]
		return depth_perm(half1, level + 1) + [level] + depth_perm(half2, level + 1)
enter = int(input())
for i in range(enter):
	length = input()
	permutation = list(map(int, input().split()))
	array = depth_perm(permutation, 0)
	output = ''
	for o in array:
		output += str(o) + ' '
	print(output)


def solve(arr, i, j, d, level):
	if i > j:
		return
	m = max(arr[i:j + 1])
	ind = arr.index(m)
	d[arr[ind]] = level
	solve(arr, i, ind - 1, d, level + 1)
	solve(arr, ind + 1, j, d, level + 1)
for testacse in range(int(input())):
	n = int(input())
	arr = [int(x) for x in input().split()]
	d = {}
	for ele in arr:
		d[ele] = 0
	solve(arr, 0, n - 1, d, 0)
	ans = []
	for ele in arr:
		ans.append(d[ele])
	print(*ans)


import math

def rec(l, l_, s, e, cnt):
	if s > e:
		return
	elif s == e:
		l_[s] = cnt
		return
	else:
		maxm = l[s]
		ind = s
		for j in range(s + 1, e + 1, 1):
			if l[j] > maxm:
				maxm = l[j]
				ind = j
		l_[ind] = cnt
		rec(l, l_, s, ind - 1, cnt + 1)
		rec(l, l_, ind + 1, e, cnt + 1)
t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	l_ = [0] * n
	rec(l, l_, 0, n - 1, 0)
	s = ''
	for elem in l_:
		s += str(elem) + ' '
	print(s[:-1])


def tree(temp, i):
	m = arr.index(max(temp))
	r[m] = i
	t = temp.index(max(temp))
	if t > 0:
		tree(temp[0:t], i + 1)
	if t < len(temp) - 1:
		tree(temp[t + 1:len(temp)], i + 1)
	return
t = int(input())
for j in range(t):
	l = int(input())
	arr = list(map(int, input().split()))
	r = [-1] * l
	tree(arr, 0)
	print(*r, sep=' ')


t = int(input())

def depth(n, start, end):
	if start == end:
		newVet[start] = n
	else:
		max = -1
		j = start
		while j <= end:
			if a[j] > max:
				max = a[j]
				div = j
			j += 1
		newVet[div] = n
		if start <= div - 1:
			depth(n + 1, start, div - 1)
		if div + 1 <= end:
			depth(n + 1, div + 1, end)
for i in range(t):
	length = int(input())
	a = [int(n) for n in input().split()]
	newVet = [-1] * length
	depth(0, 0, length - 1)
	print(*newVet)


from sys import stdin, stdout
from collections import Counter, deque
import math

class Node:

	def __init__(self, data):
		self.left = None
		self.right = None
		self.data = data
for test in range(int(input())):
	n = int(int(stdin.readline()))
	arr = list(map(int, stdin.readline().split()))
	d = [0] * n

	def haha(arr, i, st, en):
		if arr[st:en]:
			maxi = arr.index(max(arr[st:en]))
			d[maxi] = i
			haha(arr, i + 1, st, maxi)
			haha(arr, i + 1, maxi + 1, en)
	haha(arr, 0, 0, n)
	print(*d)


import sys
sys.setrecursionlimit(10 ** 9)
t = int(input())

def dfs(s, d):
	if len(s) == 0:
		return
	if len(s) == 0:
		nums[s[0]] = d
		return
	m = max(s)
	nums[m] = d
	b = []
	for i in s:
		if i == m:
			dfs(b, d + 1)
			b = []
		else:
			b.append(i)
	if len(b) > 0:
		dfs(b, d + 1)
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [-1 for i in range(n)]
	nums = [-1 for i in range(n + 1)]
	dfs(a, 0)
	for i in range(n):
		x = nums[a[i]]
		ans[i] = x
	print(*ans)


__version__ = '0.1'
__date__ = '2021-03-13'
import sys

def rec_tree(a, k):
	if len(a) == 1:
		return [k]
	curr = a.index(max(a))
	n = len(a)
	if curr > 0:
		left = rec_tree(a[:curr], k + 1)
	else:
		left = []
	if curr < n - 1:
		right = rec_tree(a[curr + 1:], k + 1)
	else:
		right = []
	return left + [k] + right

def solve(n, a):
	return ' '.join(map(str, rec_tree(a, 0)))

def main(argv=None):
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		print(solve(n, a))
	return 0
STATUS = main()
sys.exit(STATUS)


def get_max_value(arr, left, right):
	max_value_id = left
	for idx in range(left, right + 1):
		if arr[max_value_id] < arr[idx]:
			max_value_id = idx
	return max_value_id

def generate_tree(arr, depth, left, right, current_depth=0):
	idx = get_max_value(arr, left, right)
	depth[arr[idx]] = current_depth
	if idx != left:
		depth = generate_tree(arr, depth, left, idx - 1, current_depth + 1)
	if idx != right:
		depth = generate_tree(arr, depth, idx + 1, right, current_depth + 1)
	return depth
n = int(input())
for _ in range(n):
	input()
	permutation = [int(i) for i in input().split()]
	depth = {}
	depth = generate_tree(permutation, depth, 0, len(permutation) - 1)
	permutation_depth = [str(depth[i]) for i in permutation]
	print(' '.join(permutation_depth))


def depth(l, level):
	tree.append(max(l))
	zone.append(level)
	level = level + 1
	left = l[:l.index(max(l))]
	right = l[l.index(max(l)) + 1:]
	if len(left) > 0:
		depth(left, level)
	if len(right) > 0:
		depth(right, level)
test_cases = int(input())
while test_cases > 0:
	list_l = int(input())
	l = list(map(int, input().split()))
	tree = []
	zone = []
	depth(l, 0)
	answer = []
	for i in l:
		j = tree.index(i)
		answer.append(zone[j])
	answerstr = ' '.join(map(str, answer))
	print(answerstr)
	test_cases = test_cases - 1


def tr(a, n):
	if a != []:
		i = a.index(max(a))
		a[i] = n
		return tr(a[:i], n + 1) + [n] + tr(a[i + 1:], n + 1)
	else:
		return a

def amin():
	for _ in range(int(input())):
		n = int(input())
		a = list(map(int, input().split()))
		c = tr(a, 0)
		print(' '.join(map(str, c)))
amin()


def dfs(permutation):
	global newDict, counter
	maxa = max(permutation)
	if len(permutation) == 1:
		newDict.update({maxa: counter})
		return
	else:
		pos = permutation.index(maxa)
		dfs([maxa])
		counter += 1
		if pos != 0:
			dfs(permutation[:pos])
		if pos + 1 < len(permutation):
			dfs(permutation[pos + 1:])
		counter -= 1
t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	counter = 0
	newDict = {}
	dfs(arr)
	for j in arr:
		print(newDict[j], end=' ')


import sys
input = sys.stdin.readline

def solve(s, e, c):
	if s > e:
		return
	if s == e:
		ans[s] = c
		return
	m = a[s:e + 1].index(max(a[s:e + 1])) + s
	ans[m] = c
	solve(s, m - 1, c + 1)
	solve(m + 1, e, c + 1)
for nt in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [-1] * n
	solve(0, n - 1, 0)
	print(*ans)


import math

def bs(level, c, l, i, j):
	if i < j:
		m = -1000
		ind = -1
		x = i
		y = j
		for i in range(i, j):
			if m < l[i]:
				ind = i
				m = l[i]
		level[ind] = c
		c += 1
		bs(level, c, l, x, ind)
		bs(level, c, l, ind + 1, y)
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	level = [0] * n
	c = 0
	bs(level, c, l, 0, n)
	print(*level)


depths = []

def make_tree(seq, current_depth, shift_idx):
	if len(seq) == 0:
		return
	max_index = shift_idx
	max_val = 1
	for (idx, val) in enumerate(seq):
		idx += shift_idx
		if val > max_val:
			max_val = val
			max_index = idx
	depths[max_index] = current_depth
	if len(seq) <= 1:
		return
	make_tree(seq[:max_index - shift_idx], current_depth + 1, shift_idx)
	make_tree(seq[max_index + 1 - shift_idx:], current_depth + 1, max_index + 1)
n_tests = int(input())
for t in range(n_tests):
	input()
	in_seq = input().split(' ')
	in_seq = list(map(int, in_seq))
	depths = [-1 for x in in_seq]
	make_tree(in_seq, 0, 0)
	print(' '.join(list(map(str, depths))))


def getdepth(l, arr):
	if not arr:
		return
	mx = max(arr)
	ind = arr.index(mx)
	d[mx] = l
	getdepth(l + 1, arr[:ind])
	getdepth(l + 1, arr[ind + 1:])
for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	d = dict()
	getdepth(0, a)
	for i in a:
		print(d[i], end=' ')
	print()


def f(ls, cnt, dic):
	if len(ls) <= 0:
		return
	ind = ls.index(max(ls))
	dic[ls[ind]] = cnt
	f(ls[:ind], cnt + 1, dic)
	f(ls[ind + 1:], cnt + 1, dic)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	dic = {}
	f(a, 0, dic)
	for i in a:
		print(dic[i], end=' ')
	print()


def deez(left, right, middle, c):
	if left < middle or middle < right:
		if left < middle:
			t = l.index(max(l[left:middle]))
			l1[t] = c
			deez(left, middle, t, c + 1)
		if middle + 1 < right:
			k = l.index(max(l[middle + 1:right]))
			l1[k] = c
			deez(middle + 1, right, k, c + 1)
	else:
		return
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l1 = [0] * n
	w = l.index(max(l))
	deez(0, n, w, 1)
	print(*l1)


def divide(arr, x, output):
	parts = []
	largest_index = arr.index(max(arr))
	parts.append(list(arr[0:largest_index]))
	parts.append(list(arr[largest_index + 1:len(arr)]))
	output[arr[largest_index]] = x
	if len(parts[0]) > 0:
		divide(parts[0], x + 1, output)
	if len(parts[1]) > 0:
		divide(parts[1], x + 1, output)
	return output

def main():
	np = int(input(''))
	permutations = []
	for x in range(0, np):
		leng = input('')
		permutation = input('')
		permutations.append(list(map(int, permutation.split(' '))))
	for x in range(0, len(permutations)):
		out = divide(permutations[x], 0, {})
		for y in range(0, len(permutations[x])):
			print(out[int(permutations[x][y])], ' ', end='')
		print('')
main()


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()
	p = {}
	for (i, x) in enumerate(a):
		p[x] = i
	res = [0] * n

	def dfs(l, r, c=0):
		mx = -1
		ind = -1
		for i in range(l, r):
			if a[i] > mx:
				ind = i
				mx = a[i]
		res[mx - 1] = c
		if ind - l > 0:
			dfs(l, ind, c + 1)
		if r - ind - 1 > 0:
			dfs(ind + 1, r, c + 1)
	dfs(0, n)
	ans = [-1] * n
	for (i, x) in enumerate(res):
		ans[p[i + 1]] = x
	print(*ans)


from typing import Tuple, List

def read_test_case() -> Tuple[str, List[int]]:
	array_size = input()
	test_array = [int(i) for i in input().split(' ')]
	return (array_size, test_array)

def array_to_depth(array: List[int], size: int, depth: int) -> str:
	index = array.index(max(array))
	left = array_to_depth(array[:index], index, depth + 1) if index != 0 else ''
	right = array_to_depth(array[index + 1:], size - index - 1, depth + 1) if index != size - 1 else ''
	return f'{left} {depth} {right}'.strip()
number_of_test_cases = int(input())
for _ in range(number_of_test_cases):
	(size, array) = read_test_case()
	result = array_to_depth(array, int(size), 0)
	print(result)


cases = int(input())
for _ in range(cases):
	n = int(input())
	arr = [int(i) for i in input().strip().split()]
	ans = {}

	def solve(lo, hi, depth):
		if lo > hi:
			return
		mx = lo
		for i in range(lo, hi + 1):
			if arr[i] > arr[mx]:
				mx = i
		ans[arr[mx]] = str(depth)
		solve(lo, mx - 1, depth + 1)
		solve(mx + 1, hi, depth + 1)
	solve(0, n - 1, 0)
	print(' '.join([ans[i] for i in arr]))


from sys import stdin, stdout

def count(arr, res, lo, hi, level):
	if lo < hi:
		m = 0
		mi = -1
		for i in range(lo, hi):
			if arr[i] > m:
				m = arr[i]
				mi = i
		res[mi] = level
		count(arr, res, lo, mi, level + 1)
		count(arr, res, mi + 1, hi, level + 1)

def main():
	t = int(stdin.readline())
	for _ in range(t):
		n = int(stdin.readline())
		arr = list(map(int, stdin.readline().split()))
		res = [0] * len(arr)
		count(arr, res, 0, n, 0)
		stdout.write('%s\n' % ' '.join(map(str, res)))
main()


def rek(a, d):
	if len(a) == 1:
		return [d]
	if len(a) == 0:
		return []
	nv = -1
	for i in range(len(a)):
		if a[i] == max(a):
			nv = i
			break
	return rek(a[:nv], d + 1) + [d] + rek(a[nv + 1:], d + 1)
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ans = rek(a, 0)
	print(*ans)


def aux(length, values, x):
	if length == 0:
		return []
	elif length == 1:
		return [x]
	else:
		maximum = values.index(max(values))
		first = values[:maximum]
		last = values[maximum + 1:]
		return aux(len(first), first, x + 1) + [x] + aux(len(last), last, x + 1)

def main():
	number = int(input())
	for i in range(number):
		cont = 0
		values = []
		length_permutation = int(input())
		input_values = input().split(' ')
		for i in input_values:
			values.append(int(i))
		result = aux(length_permutation, values, cont)
		output = ''
		for i in range(len(result)):
			output += str(result[i]) + ' '
		print(output)
main()


def solve(l, r, lst, arr, cnt):
	if l <= r:
		mx = arr[l]
		index = l
		for i in range(l, r + 1):
			if lst[i] > mx:
				mx = lst[i]
				index = i
		arr[index] = cnt
		cnt += 1
		solve(l, index - 1, lst, arr, cnt)
		solve(index + 1, r, lst, arr, cnt)
	return
t = int(input())
for i in range(t):
	n = int(input())
	lst = list(map(int, input().split(' ')))
	arr = [0] * n
	solve(0, n - 1, lst, arr, 0)
	for i in range(n):
		if i == n - 1:
			print(arr[i])
		else:
			print(arr[i], end=' ')