This problem is an extension of the problem "Wonderful Coloring - 1". It has quite many differences, so you should read this statement completely.

Recently, Paul and Mary have found a new favorite sequence of integers $a_1, a_2, \dots, a_n$. They want to paint it using pieces of chalk of $k$ colors. The coloring of a sequence is called wonderful if the following conditions are met:

each element of the sequence is either painted in one of $k$ colors or isn't painted;

each two elements which are painted in the same color are different (i. e. there's no two equal values painted in the same color);

let's calculate for each of $k$ colors the number of elements painted in the color — all calculated numbers must be equal;

the total number of painted elements of the sequence is the maximum among all colorings of the sequence which meet the first three conditions.

E. g. consider a sequence $a=[3, 1, 1, 1, 1, 10, 3, 10, 10, 2]$ and $k=3$. One of the wonderful colorings of the sequence is shown in the figure.

The example of a wonderful coloring of the sequence $a=[3, 1, 1, 1, 1, 10, 3, 10, 10, 2]$ and $k=3$. Note that one of the elements isn't painted.

Help Paul and Mary to find a wonderful coloring of a given sequence $a$.


-----Input-----

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

Each test case consists of two lines. The first one contains two integers $n$ and $k$ ($1 \le n \le 2\cdot10^5$, $1 \le k \le n$) — the length of a given sequence and the number of colors, respectively. The second one contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$).

It is guaranteed that the sum of $n$ over all test cases doesn't exceed $2 \cdot 10^5$.


-----Output-----

Output $t$ lines, each of them must contain a description of a wonderful coloring for the corresponding test case.

Each wonderful coloring must be printed as a sequence of $n$ integers $c_1, c_2, \dots, c_n$ ($0 \le c_i \le k$) separated by spaces where

$c_i=0$, if $i$-th element isn't painted;

$c_i>0$, if $i$-th element is painted in the $c_i$-th color.

Remember that you need to maximize the total count of painted elements for the wonderful coloring. If there are multiple solutions, print any one.


-----Examples-----

Input
6
10 3
3 1 1 1 1 10 3 10 10 2
4 4
1 1 1 1
1 1
1
13 1
3 1 4 1 5 9 2 6 5 3 5 8 9
13 2
3 1 4 1 5 9 2 6 5 3 5 8 9
13 3
3 1 4 1 5 9 2 6 5 3 5 8 9
Output
1 1 0 2 3 2 2 1 3 3
4 2 1 3
1
0 0 1 1 0 1 1 1 0 1 1 1 0
2 1 2 2 1 1 1 1 2 1 0 2 2
1 1 3 2 1 3 3 1 2 2 3 2 0


-----Note-----

In the first test case, the answer is shown in the figure in the statement. The red color has number $1$, the blue color — $2$, the green — $3$.

Difficulty: MEDIUM
Tags: Sorting

Constructive algorithms

Data structures

Greedy algorithms
Skill types: Sorting

Data structures

Greedy algorithms

Starter code:

Solutions:
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	arr = list(map(int, input().split()))
	index = {}
	for i in range(n):
		if arr[i] in index:
			index[arr[i]].append(i)
		else:
			index[arr[i]] = [i]
	brr = list(index.values())
	(group, temp) = ([], [])
	for i in range(len(brr)):
		if len(brr[i]) < k:
			temp += brr[i]
			if len(temp) >= k:
				group.append(temp[:k])
				temp = temp[k:]
		else:
			group.append(brr[i])
	ans = [0] * n
	for num in group:
		for i in range(k):
			ans[num[i]] = i + 1
	for num in ans:
		print(num, end=' ')
	print()


import sys

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

def solve(n, k, arr):
	store = {}
	final = [0 for i in range(n)]
	for (i, ele) in enumerate(arr):
		if ele not in store:
			store[ele] = [i]
		else:
			store[ele].append(i)
	rem = []
	for ele in store:
		length = len(store[ele])
		if length >= k:
			current = 1
			for i in range(k):
				final[store[ele][i]] = current
				current += 1
		else:
			present = len(rem)
			req = k - present
			if length <= req:
				rem.extend(store[ele])
				newArr = []
			else:
				newArr = store[ele][req:]
				rem.extend(store[ele][:req])
			if len(rem) == k:
				current = 1
				for j in rem:
					final[j] = current
					current += 1
				rem = newArr
	if len(rem) == k:
		current = 1
		for j in rem:
			final[j] = current
			current += 1
	sys.stdout.write(' '.join(map(str, final)) + '\n')
	return
T = int(input())
while T:
	(n, k) = get_ints()
	arr = list(get_ints())
	solve(n, k, arr)
	T -= 1


R = lambda : map(int, input().split())
(t,) = R()
while t:
	t -= 1
	(n, k) = R()
	r = [0] * n
	a = []
	p = 0
	for (x, i) in sorted(zip(R(), range(n))):
		n *= x == p
		a += [i][:n < k]
		p = x
		n += 1
	for i in a[len(a) % k:]:
		n = n % k + 1
		r[i] = n
	print(*r)


from math import *
import heapq as h
from collections import Counter
mod = 1000000007

def pro(arr, k):
	freq = {}
	n = len(arr)
	ans = [0] * n
	for i in range(n):
		if arr[i] in freq:
			if len(freq[arr[i]]) == k:
				ans[i] = 0
				continue
			freq[arr[i]].append(i)
		else:
			freq[arr[i]] = [i]
	tot = 0
	for (i, j) in freq.items():
		tot = tot + len(j)
	tot = tot - tot % k
	c = 1
	for (i, j) in freq.items():
		if tot == 0:
			break
		for p in j:
			if tot == 0:
				break
			ans[p] = c
			tot -= 1
			if c == k:
				c = 1
			else:
				c += 1
	print(*ans)
t = int(input())
for i in range(t):
	(n, k) = list(map(int, input().split()))
	arr = list(map(int, input().split()))
	pro(arr, k)


import sys
from collections import Counter
sys.stdin.readline()
for line in sys.stdin:
	lsplit = line.split()
	n = int(lsplit[0])
	k = int(lsplit[1])
	nums = sys.stdin.readline().split()
	ctr = Counter(nums)
	sol = [0] * n
	cur = 0
	colors = [set() for i in range(k)]
	d = {num: set() for num in nums}
	for num in ctr:
		if ctr[num] >= k:
			for s in colors:
				s.add(num)
			for i in range(k):
				d[num].add(i)
		else:
			bak = cur
			for i in range(bak, bak + ctr[num]):
				colors[i % k].add(num)
				d[num].add(i % k)
				cur = (cur + 1) % k
	numred = len(colors[k - 1])
	for (i, s) in enumerate(colors):
		if len(s) > numred:
			num = s.pop()
			d[num].remove(i)
	for (i, num) in enumerate(nums):
		s = d[num]
		if len(s) > 0:
			col = s.pop()
			sol[i] = col + 1
	print(*sol)


t = int(input())
for test in range(t):
	(n, k) = map(int, input().split())
	l = list(map(int, input().split()))
	l2 = {}
	l3 = []
	ans = []
	d = {}
	l4 = {}
	c = 0
	for i in range(n):
		if l[i] not in d.keys():
			d[l[i]] = 1
		else:
			d[l[i]] += 1
	for key in d:
		if d[key] >= k:
			l2[key] = k
		else:
			l4[key] = []
			c += d[key]
			l3.extend([key] * d[key])
	if c < k:
		for i in range(n):
			if l[i] in l2:
				if l2[l[i]] == 0:
					print(0, end=' ')
				else:
					print(l2[l[i]], end=' ')
					l2[l[i]] -= 1
			else:
				print(0, end=' ')
		print()
		continue
	else:
		ind = 1
		l3.sort()
		for j in range(c - c % k):
			l4[l3[-1]].append(ind)
			l3.pop()
			ind += 1
			if ind > k:
				ind = 1
		i = 0
		for i in range(n):
			if l[i] in l2:
				if l2[l[i]] == 0:
					print(0, end=' ')
				else:
					print(l2[l[i]], end=' ')
					l2[l[i]] -= 1
			elif len(l4[l[i]]) == 0:
				print(0, end=' ')
			else:
				print(l4[l[i]].pop(), end=' ')
		print()


from sys import stdin

def sortt(aa):
	return arr[aa]
for _ in range(int(stdin.readline())):
	(n, k) = map(int, stdin.readline().split())
	arr = list(map(int, stdin.readline().split()))
	d = [[] for i in range(n + 1)]
	ans = [0 for i in range(n)]
	el = []
	s = 0
	j = 0
	for i in arr:
		if len(d[i]) < k:
			d[i].append(j)
			el.append(j)
			s += 1
		j += 1
	a = s // k
	t = a * k
	el.sort(key=sortt)
	cl = 1
	for i in range(t):
		ans[el[i]] = cl
		cl += 1
		if cl == k + 1:
			cl = 1
	print(*ans)


T = int(input())
from collections import defaultdict
for _ in range(T):
	(N, K) = map(int, input().split())
	A = list(map(int, input().split()))
	ans = [0] * N
	dic = defaultdict(lambda : [])
	for (i, a) in enumerate(A):
		dic[a].append(i)
	stack = []
	for v in dic.values():
		if len(v) < K:
			for i in v:
				stack.append(i)
		else:
			for (j, i) in enumerate(v[:K]):
				ans[i] = j + 1
	while len(stack) % K:
		stack.pop()
	for (j, i) in enumerate(stack):
		ans[i] = j % K + 1
	print(*ans)


import sys
input = sys.stdin.readline
t = int(input())
while t > 0:
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	d = {}
	for i in range(n):
		if a[i] not in d:
			d[a[i]] = []
		d[a[i]].append(i)
	ans = [0] * n
	temp = []
	for x in d:
		for y in range(min(k, len(d[x]))):
			temp.append(d[x][y])
			if len(temp) == k:
				for z in range(k):
					ans[temp[z]] = z + 1
				temp = []
	print(*ans)
	t -= 1


import sys
import math
import collections
dy = [1, 0, -1, 0]
dx = [0, 1, 0, -1]
r = sys.stdin.readline
for _ in range(int(r())):
	(N, K) = map(int, r().split())
	L = list(map(int, r().split()))
	LL = []
	ans = [0] * (N + 1)
	d = {}
	can = 0
	for i in range(N):
		LL.append([L[i], i])
		try:
			d[L[i]] += 1
		except:
			d[L[i]] = 1
		if d[L[i]] <= K:
			can += 1
	can //= K
	can -= 1
	LL.sort()
	dic = {}
	idx = 1
	for i in range(N):
		try:
			dic[LL[i][0]] += 1
		except:
			dic[LL[i][0]] = 1
		if dic[LL[i][0]] > K:
			continue
		ans[LL[i][1]] = idx
		if idx >= K:
			if can:
				can -= 1
				idx = 0
			else:
				break
		idx += 1
	for i in range(N):
		print(ans[i], end=' ')
	print()


from collections import Counter, defaultdict
T = int(input())
for _ in range(T):
	(n, k) = map(int, input().split(' '))
	A = list(map(int, input().split(' ')))
	M = defaultdict(list)
	for i in range(len(A)):
		M[A[i]].append(i)
	C = Counter(A)
	G = list(((c, v) for (v, c) in C.items()))
	G.sort(key=lambda e: -e[0])
	R = [0] * n
	r = k
	N = []
	for g in range(len(G)):
		(c, v) = G[g]
		L = M[v]
		if c >= k:
			for i in range(k):
				R[L.pop()] = i + 1
			r = k
		else:
			for _ in range(len(L)):
				N.append((L.pop(), r))
				r -= 1
				if r == 0:
					r = k
				if len(N) == k:
					for (i, c) in N:
						R[i] = c
					N = []
	print(' '.join((str(r) for r in R)))


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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import collections, string, bisect, re, random, queue, itertools, statistics, math
from collections import *
from bisect import *
from string import *
from itertools import *
from statistics import *
from math import *
from re import *
from queue import *

class Stack:

	def __init__(self):
		self.items = []

	def push(self, item):
		self.items.append(item)

	def pop(self):
		return self.items.pop()

	def empty(self):
		return self.items == []

	def size(self):
		return len(self.items)

	def at(self, idx):
		try:
			return self.items[idx]
		except:
			return -1

class priority_queue(object):

	def __init__(self):
		self.queue = []

	def __str__(self):
		return ' '.join([str(i) for i in self.queue])

	def empty(self):
		return len(self.queue) == 0

	def push(self, data):
		self.queue.append(data)

	def pop(self):
		try:
			max = 0
			for i in range(len(self.queue)):
				if self.queue[i] > self.queue[max]:
					max = i
			item = self.queue[max]
			del self.queue[max]
			return item
		except IndexError:
			print()
			exit()
mod = int(1000000000.0 + 7)
imax = float('inf')
imin = float('-inf')
true = True
false = False
N = int(100000.0 + 10)
none = None
inp = lambda : input()
I = lambda : int(inp())
M = lambda : map(int, inp().split())
MS = lambda : map(str, inp().split())
S = lambda : list(MS())
L = lambda : list(M())

def IO():
	try:
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('uttar.txt', 'w')
	except:
		pass
IO()

def kabraji_ka_totka():
	(n, k) = L()
	arr = L()
	cnt = [0] * (n + 1)
	ind = []
	for (i, j) in enumerate(arr):
		if cnt[j] < k:
			ind.append((j, i))
		cnt[j] += 1
	ind.sort()
	res = 0
	m = [0] * n
	m1 = len(ind) - len(ind) % k
	for (x, i) in ind[:m1]:
		m[i] = res + 1
		res = (res + 1) % k
	print(*m)
for i in range(I()):
	kabraji_ka_totka()


from collections import *
from math import *
TT = int(input())
for y in range(TT):
	(n, m) = map(int, input().split())
	lst = list(map(int, input().split()))
	d1 = defaultdict(int)
	d2 = defaultdict(list)
	ans = [0] * n
	for i in range(n):
		d1[lst[i]] += 1
		d2[lst[i]].append(i)
	cur = []
	cl = 0
	for i in d1:
		if d1[i] >= m:
			for j in range(m):
				ans[d2[i][j]] = j + 1
		else:
			for j in d2[i]:
				cur.append(j)
				cl += 1
				if cl == m:
					for lp in range(m):
						ans[cur[lp]] = lp + 1
					cur = []
					cl = 0
	print(*ans)


import sys
from bisect import bisect_left as lb
from collections import deque
from queue import PriorityQueue as pq
from math import *
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_())
ap = lambda ab, bc, cd: ab[bc].append(cd)
li = lambda : list(input_())
pr = lambda x: print(x)
prinT = lambda x: print(x)
f = lambda : sys.stdout.flush()
inv = lambda x: pow(x, mod - 2, mod)
mod = 10 ** 9 + 7
for _ in range(ii()):
	(n, k) = il()
	a = il()
	d = {}
	for i in range(n):
		if d.get(a[i]):
			d[a[i]].append(i)
		else:
			d[a[i]] = [i]
	b = []
	for i in d:
		x = d[i]
		x.insert(0, len(x))
		b.append(x)
	b.sort(reverse=True)
	ans = [0 for i in range(n)]
	v = 1
	z = []
	for i in range(len(b)):
		y = b[i][1:]
		t1 = 0
		for j in y:
			z.append([j, v])
			if len(z) == k:
				for m in z:
					ans[m[0]] = m[1]
				z = []
			v += 1
			t1 += 1
			if v > k:
				v = 1
			if t1 == k:
				break
	print(*ans)


from collections import defaultdict
T = int(input())
for t in range(T):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	count = defaultdict(int)
	for element in a:
		count[element] += 1
	index_a = []
	for (index, element) in enumerate(a):
		index_a.append([count[element], element, index])
	index_a.sort(reverse=True)
	colors = [0 for i in range(n)]
	i = 0
	while i < n:
		(c, _, index) = index_a[i]
		if c > k:
			for i_tmp in range(i, i + k):
				(c_tmp, _, index_tmp) = index_a[i_tmp]
				colors[index_tmp] = i_tmp - i + 1
			for i_tmp in range(k, c):
				(c_tmp, _, index_tmp) = index_a[i_tmp]
				colors[index_tmp] = 0
			i += c
			continue
		for i_tmp in range(i, i + (n - i) // k * k):
			(c_tmp, _, index_tmp) = index_a[i_tmp]
			colors[index_tmp] = (i - i_tmp) % k + 1
		for i_tmp in range(i + (n - i) // k * k, n):
			(c_tmp, _, index_tmp) = index_a[i_tmp]
			colors[index_tmp] = 0
		break
	print(' '.join(map(str, colors)))


import sys
input = sys.stdin.readline

def I():
	return input().strip()

def II():
	return int(input().strip())

def LI():
	return [*map(int, input().strip().split())]
import copy, string, math, time, functools, random, fractions
from heapq import heappush, heappop, heapify
from bisect import bisect_left, bisect_right
from collections import deque, defaultdict, Counter, OrderedDict
from itertools import permutations, combinations, groupby
from operator import itemgetter
for _ in range(II()):
	(n, k) = LI()
	a = LI()
	c = Counter(a)
	ans = [0] * n
	var = 0
	for i in c.values():
		var += min(k, i)
	mex = var // k * k
	tot = 0
	dd = defaultdict(lambda : 0)
	color = 0
	(sor_ind, sor_arr) = list(zip(*sorted(enumerate(a), key=lambda x: x[1])))
	for i in range(n):
		if tot >= mex:
			break
		if dd[sor_arr[i]] >= k:
			continue
		ans[i] = color % k + 1
		color += 1
		dd[sor_arr[i]] += 1
		tot += 1
	out = [0] * n
	for i in range(n):
		out[sor_ind[i]] = ans[i]
	print(*out)


from collections import Counter, defaultdict
t = int(input())
for _ in range(t):
	(n, k) = (int(x) for x in input().split())
	a = [int(x) for x in input().split()]
	c = Counter(a)
	h = sorted(((x, i) for (i, x) in enumerate(a)))
	(p, mp, j) = (1, defaultdict(lambda : 1), k * (sum((c[x] for x in c if c[x] < k)) // k))
	for i in range(n):
		(x, y) = h[i]
		if c[x] < k:
			if j:
				j -= 1
				h[i] = (p, y)
				if p == k:
					p = 1
				else:
					p += 1
			else:
				h[i] = (0, y)
		elif mp[x] <= k:
			h[i] = (mp[x], y)
			mp[x] += 1
		else:
			h[i] = (0, y)
	u = [0] * n
	for (p, q) in h:
		u[q] = p
	print(' '.join((str(x) for x in u)))


from collections import Counter
t = int(input())
while t:
	t -= 1
	(n, k) = map(int, input().split())
	s = list(map(int, input().split()))
	tmp = [[] for i in range(n + 1)]
	num = 0
	for i in range(n):
		if len(tmp[s[i]]) < k:
			tmp[s[i]].append(i)
			num += 1
	group = num // k
	end = group * k
	z = 0
	res = [0] * n
	for i in tmp:
		for j in i:
			res[j] = z % k + 1
			z += 1
			if z == end:
				print(' '.join((str(i) for i in res)))


from math import floor, gcd, sqrt, ceil
from collections import Counter, defaultdict

def main():
	for _ in range(int(input())):
		(n, k) = map(int, input().split())
		a = list(map(int, input().split()))
		color = [0] * n
		faaltu = []
		d = defaultdict(list)
		for i in range(n):
			d[a[i]].append(i)
		for i in d:
			if len(d[i]) >= k:
				k1 = 1
				for j in d[i][:k]:
					color[j] = k1
					k1 += 1
			else:
				faaltu.extend(d[i])
		k1 = 1
		for i in faaltu[:k * (len(faaltu) // k)]:
			color[i] = k1
			k1 = (k1 + 1) % k
			if k1 == 0:
				k1 = k
		print(*color)
main()


from sys import stdin
from collections import defaultdict as dict, Counter
input = lambda : stdin.readline().strip()
linput = lambda : [*map(int, input().split())]
output = []

def lprint(*x):
	output.append(' '.join(map(str, x)))

def main():
	(n, k) = linput()
	a = linput()
	d = dict(list)
	for (i, x) in enumerate(a):
		d[x].append(i)
	ans = [0] * n
	c = 0
	for x in d:
		s = c + k
		while d[x] and c != s:
			ans[d[x].pop()] = c % k + 1
			c += 1
	c = Counter(ans)
	m = min([c[x] for x in c if x])
	for i in range(n):
		if ans[i] and c[ans[i]] > m:
			c[ans[i]] -= 1
			ans[i] = 0
	lprint(*ans)
for _ in ' ' * int(input()):
	main()
print(*output, sep='\n')


t = int(input())
for ii in range(t):
	(n, k) = map(int, input().split())
	s = list(map(int, input().split()))
	freq = {}
	for i in s:
		if i in freq:
			freq[i] += 1
		else:
			freq[i] = 1
	for i in freq:
		if freq[i] > k:
			freq[i] = k
	reversemap = {}
	colors = [0] * n
	for i in freq:
		val = freq[i]
		if val in reversemap:
			reversemap[val].append(i)
		else:
			reversemap[val] = [i]
	sm = 0
	for i in reversemap:
		if i != k:
			sm += i * len(reversemap[i])
	sm = sm - sm % k
	groups = sm // k
	index_map = {}
	cnt = 0
	for i in s:
		if i in index_map:
			index_map[i].append(cnt)
		else:
			index_map[i] = [cnt]
		cnt += 1
	if k in reversemap:
		for pos in reversemap[k]:
			cnt = 1
			for tag in index_map[pos][:k]:
				colors[tag] = cnt
				cnt += 1
	cnt = 1
	total = groups * k
	done = False
	if total > 0:
		for i in reversemap:
			if done:
				break
			if i < k:
				for val in reversemap[i]:
					if done:
						break
					for j in index_map[val]:
						colors[j] = cnt
						cnt += 1
						total -= 1
						if cnt == k + 1:
							cnt = 1
						if total == 0:
							done = True
							break
	print(*colors)


mini = 100000
tests = int(input())
mod = 10 ** 9 + 7
while tests:
	tests -= 1
	arr = list(map(int, input().split()))
	(n, k) = (arr[0], arr[1])
	arr = list(map(int, input().split()))
	d = {}
	distinct = 0
	stri = ''
	ct = 1
	loc = -1
	for i in arr:
		loc += 1
		if i in d:
			if len(d[i]) < k:
				d[i].append(loc)
				distinct += 1
			else:
				arr[loc] = 0
		else:
			d[i] = [loc]
			distinct += 1
	ct = 1
	stri = ''
	can_be_colored = distinct - int(distinct % k)
	for i in d:
		for j in d[i]:
			if can_be_colored > 0:
				can_be_colored -= 1
				col = ct % k + 1
				arr[j] = col
				ct += 1
			else:
				arr[j] = 0
	ans = ''
	for i in arr:
		ans += str(i) + ' '
	print(ans)


t = int(input())
while t:
	(s, k) = map(int, input().split())
	a = list(map(int, input().split()))
	color = [0] * s
	d = {}
	for i in range(s):
		if a[i] not in d:
			d[a[i]] = []
		d[a[i]].append(i)
	leftover = []
	for i in d:
		if len(d[i]) >= k:
			for j in range(k):
				color[d[i][j]] = j + 1
		else:
			leftover.extend(d[i])
	m = len(leftover)
	leftover = leftover[:m - m % k]
	m = len(leftover)
	c = 1
	for i in range(m):
		if c > k:
			c = 1
		color[leftover[i]] = c
		c = c + 1
	print(' '.join(list(map(str, color))))
	t = t - 1


import sys
input = sys.stdin.readline
import math
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	b = []
	for i in range(n):
		b.append([a[i], i])
	col = 0
	ans = []
	b.sort()
	last = [0] * k
	for i in range(n):
		if b[i][0] != last[col]:
			last[col] = b[i][0]
			ans.append(i)
			col = (col + 1) % k
		else:
			continue
	col = 0
	m = [0] * n
	ans = ans[:k * (len(ans) // k)]
	for i in ans:
		m[b[i][1]] = col + 1
		col = (col + 1) % k
	print(*m)


def magika(nums, cores):
	dic = {}
	temp = []
	for i in range(len(nums)):
		if nums[i] in dic:
			dic[nums[i]].append(i)
		else:
			dic[nums[i]] = [i]
	ans = [0] * len(nums)
	for k in dic.keys():
		if len(dic[k]) >= cores:
			for j in range(cores):
				ans[dic[k][j]] = j + 1
		elif len(dic[k]) >= 1:
			for x in range(len(dic[k])):
				temp.append(dic[k][x])
	count = len(temp) // cores
	p = 1
	maxi = 0
	for y in range(len(temp)):
		if maxi == count:
			break
		ans[temp[y]] = p
		if p == cores:
			maxi += 1
		p += 1
		if p == cores + 1:
			p = 1
	return ans
n = int(input())
r = [0] * n
for i in range(n):
	(elementos, cores) = map(int, input().split())
	nums = list(map(int, input().split()))
	r[i] = magika(nums, cores)
for c in r:
	for j in range(len(c)):
		if j == len(c) - 1:
			print(c[j])
		else:
			print(c[j], end=' ')


t = int(input())
while t:
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	d = {}
	ans = [0] * n
	ex = []
	for i in range(n):
		if a[i] in d:
			d[a[i]].append(i)
		else:
			d[a[i]] = []
			d[a[i]].append(i)
	for i in d:
		if len(d[i]) >= k:
			for x in range(1, k + 1):
				ans[d[i][x - 1]] = x
		else:
			ex += d[i]
		if len(ex) >= k:
			for x in range(1, k + 1):
				ans[ex[x - 1]] = x
			ex = ex[k:]
	for i in ans:
		print(i, end=' ')
	print()
	t -= 1


for i in range(int(input())):
	(c, b) = map(int, input().split())
	a = list(map(int, input().split()))
	ind = [[] for i in range(c + 1)]
	p = {}
	num = 0
	for i in range(c):
		if len(ind[a[i]]) < b:
			ind[a[i]].append(i)
			num += 1
	m = int(num / b)
	s = m * b
	i = 0
	f = False
	j = 0
	p = ['0' for i in range(c)]
	for i in ind:
		if f == True:
			break
		for q in i:
			p[q] = str(j % b + 1)
			j += 1
			if j == s:
				print(' '.join(p))
				f = True
				break
	if f == False:
		print(' '.join(p))


t = int(input())
for _ in range(t):
	(n, k) = list(map(int, input().split()))
	ls = list(map(int, input().split()))
	memo = {}
	for i in range(n):
		try:
			memo[ls[i]].append(i)
		except KeyError:
			memo[ls[i]] = [i]
	count = 0
	for (key, value) in memo.items():
		if len(value) > k:
			count += k
			memo[key] = value[:k]
		else:
			count += len(value)
	count = count // k
	colors = [count for i in range(k)]
	c = 0
	ls = [0 for i in range(n)]
	positions = list(memo.values())
	positions.sort(key=len, reverse=True)
	for lst in positions:
		for position in lst:
			if colors[c]:
				ls[position] = c + 1
				colors[c] -= 1
				c += 1
				if c == k:
					c = 0
			else:
				break
	for color in ls:
		print(color, end=' ')
	print()


from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	(n, k) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	b = [[]]
	b.clear()
	for i in range(len(a)):
		b.append([a[i], i])
	b.sort()
	c = [-1 for i in range(len(a))]
	mp = {}
	baki = n
	for i in range(n):
		if b[i][0] in mp.keys():
			mp[b[i][0]] += 1
		else:
			mp[b[i][0]] = 1
		if mp[b[i][0]] > k:
			c[b[i][1]] = 0
			baki -= 1
	koyta = baki // k
	ct = 1
	for i in range(n):
		if c[b[i][1]] != -1:
			continue
		c[b[i][1]] = ct
		ct += 1
		if ct > k:
			ct = 1
			koyta -= 1
		if koyta <= 0:
			break
	for i in c:
		if i == -1:
			print(0)
		else:
			print(i)


from collections import Counter, defaultdict
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	l = list(map(int, input().split()))
	for i in range(n):
		l[i] = (l[i], i)
	l.sort()
	ans = [0 for i in range(n)]
	i = 0
	cnt = 1
	while i < n:
		if cnt > k:
			cnt = 1
		z = 1
		ans[l[i][1]] = cnt
		cnt += 1
		j = i + 1
		f = False
		while j < n and l[j][0] == l[j - 1][0]:
			if z >= k:
				f = True
				break
			if cnt > k:
				cnt = 1
			ans[l[j][1]] = cnt
			cnt += 1
			j += 1
			z += 1
			if cnt > k:
				cnt = 1
			if z >= k:
				f = True
				break
		if f:
			while j < n and l[j][0] == l[j - 1][0]:
				j += 1
		i = j
	d = Counter(ans)
	f = float('inf')
	for p in d.keys():
		if p != 0:
			f = min(f, d[p])
	d1 = defaultdict(int)
	for i in range(len(ans)):
		if d1[ans[i]] >= f:
			ans[i] = 0
		else:
			d1[ans[i]] += 1
	print(*ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	arr = list(map(int, input().split()))
	store = [0 for i in range(n + 1)]
	stack = [[] for i in range(n + 1)]
	counted = [0 for i in range(n + 1)]
	for i in range(n):
		if counted[arr[i]] < k:
			counted[arr[i]] += 1
			stack[arr[i]].append(i)
	queue = []
	for i in range(n + 1):
		for j in stack[i]:
			queue.append(j)
	l = len(queue)
	r = l // k * k
	i = 0
	ans = [0 for i in range(n)]
	for i in range(0, r, k):
		count = 0
		for j in range(i, i + k):
			ans[queue[j]] = count + 1
			count += 1
	print(*ans)


import sys
import math
import random
from queue import PriorityQueue as PQ
from bisect import bisect_left as BSL
from bisect import bisect_right as BSR
from collections import OrderedDict as OD
from collections import Counter
from itertools import permutations
mod = 1000000007
sys.setrecursionlimit(1000000)
try:
	sys.stdin = open('actext.txt', 'r')
	OPENFILE = 1
except:
	pass

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

def palindrome(s):
	mid = len(s) // 2
	for i in range(mid):
		if s[i] != s[len(s) - i - 1]:
			return False
	return True

def check(i, n):
	if 0 <= i < n:
		return True
	else:
		return False

def next_ind(i, k):
	if i == k + 1:
		return 1
	else:
		return i
t = int(input())
for tt in range(t):
	(n, k) = get_ints()
	arr = list(get_ints())
	mp = {}
	for (num, i) in enumerate(arr):
		if i not in mp:
			mp[i] = set()
		if len(mp[i]) + 1 <= k:
			mp[i].add(num)
	sm = 0
	for i in mp.values():
		sm += len(i)
	sm = sm // k
	need = sm * k
	mp = sorted(mp.items(), key=lambda x: len(x[1]), reverse=True)
	ind = 0
	ans = [0 for i in range(n)]
	for (i, j) in mp:
		for k1 in j:
			ind = next_ind(ind + 1, k)
			if need == 0:
				break
			need -= 1
			ans[k1] = ind
	print(*ans)


def solve():
	(n, k) = map(int, input().split())
	cnt = []
	for _ in range(n):
		cnt.append([])
	ind = 0
	for i in input().split():
		i = int(i)
		cnt[i - 1].append(ind)
		ind += 1
	now = 1
	new_a = [0] * n
	cnt_colors = [0] * k
	for i in range(n):
		for x in range(len(cnt[i])):
			if x == k:
				break
			cur = cnt[i][x]
			new_a[cur] = now
			cnt_colors[now - 1] += 1
			now += 1
			if now > k:
				now = 1
	need = min(cnt_colors)
	for i in range(n):
		if new_a[i] > 0:
			if cnt_colors[new_a[i] - 1] > need:
				cnt_colors[new_a[i] - 1] -= 1
				new_a[i] = 0
	print(*new_a)
t = int(input())
for _ in range(t):
	solve()


from collections import Counter as co, defaultdict as df
from copy import deepcopy

def good(frl, k, n):
	ans = [0] * n
	i = 0
	valid = True
	ln = len(frl)
	tmp = []
	for i in frl:
		i = i[1]
		if len(i) >= k:
			for j in range(k):
				ans[i[j]] = j + 1
		else:
			tmp.extend(i)
	times = len(tmp) // k
	while times:
		for i in range(k):
			ans[tmp.pop()] = i + 1
		times -= 1
	return (ans, valid)
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	l = list(map(int, input().split()))
	uq = df(list)
	for i in range(len(l)):
		uq[l[i]].append(i)
	frl = sorted([[x, y] for (x, y) in uq.items()], key=lambda x: len(x[1]), reverse=1)
	ans = [0] * n
	zc = float('inf')
	(ans, __) = good(frl, k, n)
	print(*ans)


t = int(input())
from collections import Counter

def solve():
	(n, k) = map(int, input().split())
	lst = list(map(int, input().split()))
	cnt = {elem: [0, []] for elem in lst}
	for (i, elem) in enumerate(lst):
		cnt[elem][0] += 1
		cnt[elem][1].append(i)
	less = []
	col = 0
	coloring = [0 for _ in range(n)]
	color = 1
	for (key, (occ, indices)) in cnt.items():
		if occ >= k:
			for (i, idx) in enumerate(indices[:k]):
				coloring[idx] = i + 1
		else:
			less += indices
	extra = len(less) % k
	for (i, idx) in enumerate(less[extra:]):
		coloring[idx] = i % k + 1
	print(*coloring)
for _ in range(t):
	solve()


R = lambda : map(int, input().split())
(t,) = R()
while t:
	t -= 1
	(n, k) = R()
	d = {}
	r = [0] * n
	i = j = 0
	for x in R():
		l = d.setdefault(x, [])
		l += ([], [i])[len(l) < k]
		i += 1
	for i in (a := [i for x in d for i in d[x]])[:len(a) // k * k]:
		j = j % k + 1
		r[i] = j
	print(*r)


from collections import Counter
t = int(input())

def solve(s, k):
	n = len(s)
	indices = {}
	for (i, x) in enumerate(s):
		if x not in indices:
			indices[x] = []
		indices[x].append(i)
	result = [0] * n
	S = []
	for (x, L) in indices.items():
		if len(L) >= k:
			for i in range(k):
				result[L[i]] = i + 1
		else:
			for i in L:
				S.append(i)
	N = len(S)
	for i in range(0, N, k):
		if i + k <= N:
			for j in range(k):
				result[S[i + j]] = j + 1
	return ' '.join([str(x) for x in result])
for test in range(t):
	(n, k) = [int(x) for x in input().split()]
	s = [int(x) for x in input().split()]
	print(solve(s, k))


import sys
from math import floor, gcd, factorial
from collections import deque
input = sys.stdin.readline

def printf(x, end='\n'):
	sys.stdout.write(str(x) + end)

def main():
	T = 1
	T = int(input())

	def solve(t):
		last_stored = 0
		value = [0, False]
		rr = -1
		arr = list(map(int, input().split()))
		(n, k) = (arr[0], arr[1])
		arr = list(map(int, input().split()))
		dict = {}
		for i in range(n):
			if arr[i] in dict.keys():
				dict[arr[i]].append(i)
			else:
				dict[arr[i]] = [i]
		h = arr.copy()
		h.sort()
		curr_elem = h[0]
		curr_count = 0
		count = []
		for i in range(n):
			if h[i] == curr_elem:
				curr_count += 1
			else:
				count.append((curr_count, curr_elem))
				curr_count = 1
				curr_elem = h[i]
		count.append((curr_count, h[-1]))
		count.sort()
		color = [0] * n
		count.reverse()
		w = len(count)
		x = 0
		while x < w:
			(a, b) = count[x]
			if b == value[0]:
				a -= last_stored + 1
				tt = last_stored + 1
				rr = value[0]
				value[0] = 0
				value[1] = False
			if a >= k:
				for z in range(k):
					color[dict[b][z]] = z + 1
				x += 1
				continue
			else:
				j = x + 1
				stack = deque()
				stack.append((a, b))
				su = a
				while su != k and j < w:
					(c, d) = count[j]
					if su + c > k:
						x = j
						stack.append((k - su, d))
						last_stored = k - su - 1
						value[0] = d
						su = k
					elif su + c == k:
						x = j + 1
						stack.append((c, d))
						su = k
					else:
						stack.append((c, d))
						su += c
					j += 1
				if su == k:
					sss = k
					while stack:
						(e, f) = stack.pop()
						if f == rr:
							for g in range(e):
								color[dict[f][g + tt]] = sss
								sss -= 1
						else:
							for g in range(e):
								color[dict[f][g]] = sss
								sss -= 1
				else:
					break
		print(*color)
	for i in range(T):
		solve(i + 1)
	pass
main()


t = int(input())
for i in range(t):
	(length, colors_num) = map(int, input().split())
	numbers = list(map(int, input().split()))
	numbers_dict = {}
	counter = 0
	for number in numbers:
		if number not in numbers_dict:
			numbers_dict[number] = [counter]
		else:
			numbers_dict[number].append(counter)
		counter += 1
	stock = []
	for number in numbers_dict:
		if len(numbers_dict[number]) < colors_num:
			stock += numbers_dict[number]
		else:
			stock += numbers_dict[number][:colors_num]
	painting = [0] * length
	stock = stock[:len(stock) - len(stock) % colors_num]
	color = 0
	for index in stock:
		if color == colors_num:
			color = 1
		else:
			color += 1
		painting[index] = color
	print(*painting)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	v = [[] for i in range(n + 1)]
	for i in range(n):
		v[a[i]].append(i)
	res = [0 for i in range(n)]
	j = 0
	for i in range(n + 1):
		if len(v[i]) >= k:
			for ind in range(k):
				res[v[i][ind]] = ind + 1
		else:
			for x in v[i]:
				res[x] = j % k + 1
				j += 1
	mp = [0 for i in range(k + 1)]
	for i in range(n):
		if res[i] != 0:
			mp[res[i]] += 1
	mn = 10 ** 9 + 7
	for i in range(1, k + 1):
		mn = min(mn, mp[i])
	for i in range(n):
		if res[i] != 0:
			if mp[res[i]] > mn:
				mp[res[i]] -= 1
				res[i] = 0
	print(*res)


from collections import defaultdict
for i in range(int(input())):
	(n, k) = map(int, input().split())
	s = list(map(int, input().split()))
	mp = defaultdict(list)
	for j in range(n):
		mp[s[j]].append(j)
		s[j] = 0
	m = 1
	dic = {}
	mn_occ = int(1000000000.0)
	for val in mp.values():
		m = m % k
		if m == 0:
			m = k
		temp_ln = len(val)
		mx = min(k, temp_ln)
		for i in range(mx):
			m = m % k
			if m == 0:
				m = k
			s[val[i]] = m
			dic[m] = dic.get(m, 0) + 1
			m += 1
	for val in dic.values():
		mn_occ = min(mn_occ, val)
	for idx in range(n):
		if dic.get(s[idx], -1) > mn_occ:
			dic[s[idx]] = dic[s[idx]] - 1
			s[idx] = 0
	print(*s)


from collections import defaultdict as dt
T = int(input())
for t in range(T):
	(n, k) = map(int, input().split())
	d = dt(list)
	arr = list(map(int, input().split()))
	for i in range(n):
		if len(d[arr[i]]) < k:
			d[arr[i]].append(i)
	m = 0
	for key in d.keys():
		m += len(d[key])
	m -= m % k
	c = 0
	ans = [0] * n
	for (key, ind) in d.items():
		for i in ind:
			c += 1
			ans[i] = c
			c = c % k
			m -= 1
			if not m:
				break
		if not m:
			break
	for i in ans:
		print(i, end=' ')
	print()


R = lambda : map(int, input().split())
(t,) = R()
while t:
	t -= 1
	(n, k) = R()
	r = [0] * n
	a = [[] for _ in r]
	i = 0
	for x in R():
		a[x - 1] += (i,)
		i += 1
	for j in (a := [i for x in a for i in x[:k]])[:len(a) // k * k]:
		i = i % k + 1
		r[j] = i
	print(*r)


import typing
from collections import Counter

def solve(n: int, k: int, a: typing.List[int]) -> typing.NoReturn:
	c = Counter(a)
	for x in a:
		c[x] = min(c[x], k)
	b = []
	for i in range(n):
		x = a[i]
		if not c[x]:
			continue
		c[x] -= 1
		b.append(i)
	b.sort(key=lambda i: -a[i])
	b = b[:len(b) // k * k]
	color = [0] * n
	c = 1
	for i in b:
		color[i] = c
		c = c % k + 1
	print(*color)

def main() -> typing.NoReturn:
	t = int(input())
	for _ in range(t):
		(n, k) = map(int, input().split())
		(*a,) = map(int, input().split())
		solve(n, k, a)
main()


def solve():
	(n, k) = map(int, input().split())
	a = [int(x) for x in input().split()]
	d = {}
	for (i, b) in enumerate(a):
		if b in d:
			if len(d[b]) == k:
				continue
			d[b].append(i)
		else:
			d[b] = [i]
	s = []
	ans = [0 for _ in range(n)]
	for b in d:
		if len(d[b]) == k:
			c = 1
			for i in d[b]:
				ans[i] = c
				c += 1
		else:
			s += d[b]
	l = len(s)
	l = l // k * k
	c = 1
	for i in range(l):
		ans[s[i]] = c
		c += 1
		if c == k + 1:
			c = 1
	print(' '.join((str(x) for x in ans)))
for _ in range(int(input())):
	solve()


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = list(input().split())
	count = {}
	ans = [0] * n
	tempb = 0
	for i in s:
		if i not in count:
			count[i] = 0
		count[i] += 1
	temp = {}
	for (i, j) in count.items():
		if j >= k:
			temp[i] = 1
		else:
			tempb += j
	cur = 0
	for i in sorted([(j, i) for (i, j) in enumerate(s)]):
		if i[0] in temp:
			if temp[i[0]] <= k:
				ans[i[1]] = temp[i[0]]
				temp[i[0]] += 1
		elif tempb // k * k > cur:
			ans[i[1]] = cur % k + 1
			cur += 1
	print(*ans)


import os, sys
from io import BytesIO, IOBase
from math import log2, ceil, sqrt, gcd
from _collections import deque
import heapq as hp
from bisect import bisect_left, bisect_right
from math import cos, sin
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
mod = 10 ** 9 + 7
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	ck = [[] for _ in range(n + 1)]
	for i in range(n):
		ck[a[i]].append(i)
	a.sort()
	ans = [set() for _ in range(k)]
	i = 0
	for j in a:
		if j in ans[i]:
			continue
		ans[i].add(j)
		i += 1
		i %= k
	c = [0] * n
	ct = float('inf')
	for i in range(k):
		ct = min(ct, len(ans[i]))
	for i in range(k):
		tt = ct
		for j in ans[i]:
			c[ck[j].pop()] = i + 1
			tt -= 1
			if tt == 0:
				break
	print(*c)


from collections import defaultdict
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	pos = defaultdict(list)
	for (i, val) in enumerate(a):
		pos[val].append(i)
	c = [0 for _ in range(n)]
	leftovers = []
	for indices in pos.values():
		if len(indices) >= k:
			for i in range(k):
				c[indices[i]] = i + 1
		else:
			leftovers.extend(indices)
	for i in range(len(leftovers) // k * k):
		c[leftovers[i]] = i % k + 1
	print(' '.join(map(str, c)))


t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	w = []
	dic = {}
	l = list(map(int, input().split()))
	for i in range(n):
		el = l[i]
		w.append([el, i, 0])
		if el in dic:
			dic[el] += 1
		else:
			dic[el] = 1
	w = sorted(w)
	j = 0
	while j < n:
		for i in range(k):
			if dic[w[j][0]] > k:
				j += dic[w[j][0]] - k
				dic[w[j][0]] = k
			w[j][2] = i + 1
			j += 1
			if j >= n:
				break
	j = n - 1
	while w[j][2] != k:
		w[j][2] = 0
		j -= 1
	w.sort(key=lambda x: x[1])
	for el in w:
		print(el[2], end=' ')
	print()


from collections import defaultdict
t = int(input())
for i in range(1, t + 1):
	(n, k) = list(map(int, input().split()))
	ls = list(map(int, input().split()))
	dic = defaultdict(list)
	for (idx, num) in enumerate(ls):
		if len(dic[num]) < k:
			dic[num].append(idx)
	new_ls = [0 for _ in range(len(ls))]
	count = 0
	for num in dic:
		for idx in dic[num]:
			count += 1
	count = count // k * k
	curr_color = 1
	curr_count = 0
	check = True
	for num in dic:
		for idx in dic[num]:
			curr_count += 1
			new_ls[idx] = curr_color
			curr_color += 1
			if curr_color > k:
				curr_color = 1
			if curr_count == count:
				check = False
				break
		if not check:
			break
	print(' '.join(list(map(str, new_ls))))


import traceback
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 = IOWrapper(sys.stdin)
input = lambda : sys.stdin.readline().rstrip('\r\n')
import math
from collections import defaultdict as dfd, Counter
from functools import lru_cache
from itertools import accumulate

def geti():
	return int(input())

def gets():
	return input()

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

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

def getinps(s):
	inps = s.split()
	m = {'i': geti, 's': gets, 'il': getil, 'sl': getsl}
	if len(inps) == 1:
		return m[s]()
	return [m[k]() for k in inps]

def get2d(nrows, ncols, n=0):
	return [[n] * ncols for r in range(nrows)]

def get_acc(a):
	return list(accumulate(a))

def get_ncr(n, r, mod=10 ** 9 + 7):
	num = den = 1
	r = min(r, n - r)
	for i in range(r):
		num = num * (n - i) % mod
		den = den * (i + 1) % mod
	return num * pow(den, mod - 2, mod) % mod

def get_nc2(n):
	return n * (n - 1) // 2

def get_npr(n, r):
	if n < r:
		return 0
	return math.factorial(n) // math.factorial(r)

def put(a):
	return ' '.join(map(str, a))
inf = float('inf')
mod = 10 ** 9 + 7

def main():
	(N, K) = getil()
	nums = getil()
	box = dfd(list)
	cur = 0
	cnts = Counter(nums)
	for (n, cnt) in cnts.items():
		for _ in range(min(cnt, K)):
			box[cur].append(n)
			cur = (cur + 1) % K
	minsz = len(min(box.values(), key=len))
	ans = [0] * N
	idxs = dfd(list)
	for (i, n) in enumerate(nums):
		idxs[n].append(i)
	for col in box:
		box[col] = box[col][:minsz]
		for n in box[col]:
			p = idxs[n].pop()
			ans[p] = col + 1
	print(*ans)
try:
	Test = geti()
	answers = []
	for _ in range(Test):
		ans = main()
except Exception as e:
	print(e)
	traceback.print_exc()


import sys

def read():
	line = sys.stdin.readline().rstrip()
	if ' ' in line:
		return map(int, line.split())
	return line

def solver(n, k, s):
	count = {}
	remain = []
	colors = range(1, k + 1)
	for (i, j) in enumerate(s):
		lst = count.setdefault(j, [])
		lst.append(i)
		if len(lst) == k:
			for a in range(1, k + 1):
				ans[lst[a - 1]] = a
	for value in count.values():
		if len(value) < k:
			remain.extend(value)
	for i in range(len(remain) // k):
		for j in range(1, k + 1):
			ans[remain[i * k + j - 1]] = j
T = int(read())
for t in range(T):
	(N, K) = read()
	S = read()
	ans = [0] * N
	solver(N, K, S)
	print(' '.join(map(str, ans)))
sys.exit()


from collections import defaultdict
aa = int(input())
while aa:
	(n, k) = map(int, input().split())
	lst = list(map(int, input().split()))
	hs = defaultdict(list)
	for (ind, num) in enumerate(lst):
		hs[num].append(ind)
	new = []
	for i in hs:
		if len(hs[i]) >= k:
			new += hs[i][:k]
		else:
			new += hs[i]
	res = [0] * n
	col = 1
	tot = len(new) - len(new) % k
	for i in range(tot):
		if col > k:
			col = 1
		res[new[i]] = col
		col += 1
	aa -= 1
	print(*res)


from collections import Counter
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	l = list(map(int, input().split()))
	c = Counter(l)
	p = 0
	q = 0
	for i in c:
		if c[i] >= k:
			p += 1
		else:
			q += c[i]
	b = p + q // k
	d = {}
	for i in range(n):
		if l[i] in d:
			d[l[i]].add(i)
		else:
			d[l[i]] = set()
			d[l[i]].add(i)
	r = 1
	w = 0
	for i in d:
		if c[i] >= k:
			t = 0
			for j in d[i]:
				t += 1
				if t <= k:
					l[j] = t
				else:
					l[j] = 0
		else:
			for j in d[i]:
				if w == q // k:
					l[j] = 0
				else:
					l[j] = r
					r += 1
					if r > k:
						r = 1
						w += 1
	print(*l)


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

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
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')
ALPHA = 'abcde'
MOD = 10 ** 9 + 7
EPS = 1e-06

def Ceil(a, b):
	return a // b + int(a % b > 0)

def INT():
	return int(input())

def STR():
	return input()

def INTs():
	return tuple(map(int, input().split()))

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

def ARRSTR():
	return [i for i in input().split()]
for _ in range(INT()):
	(n, k) = INTs()
	a = ARRINT()
	res = [0 for _ in range(n)]
	memo = collections.defaultdict(list)
	for i in range(n):
		memo[a[i]] += [i]
	U = []
	for (key, val) in memo.items():
		if len(val) >= k:
			for (idx, v) in enumerate(val[:k]):
				res[v] = idx + 1
		else:
			U += val
	idx = 0
	while idx + k <= len(U):
		for i in range(idx, idx + k):
			res[U[i]] = i + 1 - idx
		idx += k
	print(*res)


t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	nums = list(map(int, input().split()))
	d = {}
	for i in nums:
		d[i] = d.get(i, 0) + 1
	d = {x: k for (x, y) in d.items() if y >= k}
	lst = [i for i in nums if i not in d]
	lst.sort()
	dp = {i: [] for i in lst}
	temp = 0
	for i in lst:
		dp[i].append(temp % k + 1)
		temp += 1
	ans = nums.copy()
	for i in range(len(nums)):
		if nums[i] not in d:
			ans[i] = dp[nums[i]].pop()
		elif d[nums[i]] > 0:
			ans[i] = d[nums[i]]
			d[nums[i]] -= 1
		else:
			ans[i] = 0
	if temp % k != 0:
		s = {i for i in range(1, temp % k + 1)}
		for i in range(len(ans)):
			if ans[i] in s:
				s.remove(ans[i])
				ans[i] = 0
	print(' '.join(map(str, ans)))


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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import defaultdict
from math import ceil, floor, sqrt, log2, gcd, pi
from heapq import heappush, heappop
from fractions import Fraction
from bisect import bisect_left, bisect
import sys
abc = 'abcdefghijklmnopqrstuvwxyz'
ABC = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	arr = list(map(int, input().split()))
	d = defaultdict(list)
	a = [0] * k
	ans = [0] * n
	for i in range(n):
		d[arr[i]].append(i)
	for i in d:
		if len(d[i]) > k:
			d[i] = d[i][:k]
	stack = []
	for i in d:
		while d[i]:
			stack.append(d[i].pop())
	l = len(stack)
	if l % k != 0:
		diff = l // k * k
		stack = stack[:diff]
	val = 1
	for i in stack:
		ans[i] = val
		val += 1
		if val == k + 1:
			val = 1
	print(*ans)


from math import sqrt, gcd, ceil, floor, log, factorial
from itertools import permutations, combinations
from collections import Counter, defaultdict
import collections, sys, threading
import collections, sys, threading

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

def si():
	return input()

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

def msi():
	return map(str, input().split())

def li():
	return list(mi())
t = ii()
for _ in range(t):
	(n, k) = mi()
	a = li()
	d = {}
	cnt = Counter(a)
	res = [0] * n
	rem = []
	for i in range(n):
		d[a[i]] = d.get(a[i], 0) + 1
		if cnt[a[i]] < k:
			rem.append([a[i], i])
		elif d[a[i]] <= k:
			res[i] = d[a[i]]
		else:
			res[i] = 0
	rem.sort()
	if len(rem) < k:
		for i in rem:
			res[i[1]] = 0
	else:
		ans = len(rem) // k
		inc = 1
		for i in range(len(rem)):
			if i >= ans * k:
				res[rem[i][1]] = 0
			else:
				if inc > k:
					inc = 1
				res[rem[i][1]] = inc
				inc += 1
	print(*res)


import collections
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	l = list(map(int, input().split()))
	c = {}
	for (j, i) in enumerate(l):
		if i in c:
			if len(c[i]) < k:
				c[i].append(j)
		else:
			c[i] = [j]
	d = 0
	res = [0] * n
	for i in c:
		d += len(c[i])
	(op, d) = (0, d - d % k)
	for i in c:
		for j in c[i]:
			if op >= d:
				break
			res[j] = op % k + 1
			op += 1
	print(*res)


import heapq

def solve():
	(n, k) = [int(v) for v in input().split()]
	s = [int(v) for v in input().split()]
	d = {}
	for i in range(len(s)):
		d.setdefault(s[i], []).append(i)
	answer = [0] * len(s)
	heap = []
	for (c, arr) in d.items():
		heapq.heappush(heap, (-len(arr), arr))
	order_pt = []
	while len(heap):
		(_, arr) = heapq.heappop(heap)
		if len(arr) > k:
			for (j, idx) in enumerate(arr[:k]):
				answer[idx] = j + 1
		else:
			order_pt.extend(arr)
	z = 0
	for i in range(len(order_pt) // k * k):
		answer[order_pt[i]] = i % k + 1
	print(' '.join((str(v) for v in answer)))
t = int(input())
for _ in range(t):
	solve()


from sys import stdin, stdout
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as df, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
mod = pow(10, 9) + 7
mod2 = 998244353
S1 = 'abcdefghijklmnopqrstuvwxyz'
S2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

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

def isprime(x):
	if x <= 1:
		return False
	if x in (2, 3):
		return True
	if x % 2 == 0:
		return False
	for i in range(3, int(sqrt(x)) + 1, 2):
		if x % i == 0:
			return False
	return True

def f(s):
	(first, second) = (0, 0)
	(ans, res) = (10, 10)
	for i in range(10):
		if i % 2 == 0:
			first += int(s[i])
		else:
			second += int(s[i])
		if first > second + (10 - i) // 2:
			ans = i + 1
			break
	for i in range(10):
		if i % 2 == 0:
			first += int(s[i])
		else:
			second += int(s[i])
		if first + (9 - i) // 2 < second:
			res = i + 1
			break
	return min(ans, res)
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = list(map(str, input().split()))
	d = df(list)
	for i in range(n):
		d[s[i]].append(i)
	res = [0] * n
	(cnt, ans) = (0, 0)
	ss = set(s)
	coll = 1
	for i in ss:
		if len(d[i]) < k:
			cnt += len(d[i])
	cnt = cnt // k * k
	for i in ss:
		if len(d[i]) >= k:
			j = 0
			col = 1
			while j < k and col <= k:
				res[d[i][j]] = col
				col += 1
				j += 1
		else:
			j = 0
			while j < len(d[i]) and cnt > 0:
				res[d[i][j]] = coll
				coll += 1
				if coll == k + 1:
					coll = 1
				j += 1
				cnt -= 1
	print(*res, sep=' ')


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	cnt = [0] * (n + 1)
	a = []
	for (i, x) in enumerate(map(int, input().split())):
		if cnt[x] < k:
			a.append((x, i))
		cnt[x] += 1
	a.sort()
	ans = [0] * n
	color = 0
	ra = len(a) - len(a) % k
	for (v, i) in a[:ra]:
		color = color % k + 1
		ans[i] = color
	print(*ans)


import sys
from collections import defaultdict, deque
from bisect import bisect_left, bisect_right
from math import ceil, floor, sqrt

def main():
	test = int(input())
	for idt in range(test):
		(n, k) = map(int, input().split())
		a = list(map(int, input().split()))
		cnt = defaultdict(int)
		index = defaultdict(list)
		for (i, c) in enumerate(a):
			cnt[c] += 1
			index[c].append(i)
		ans = [0] * n
		(geq, le) = ([], [])
		for (key, v) in cnt.items():
			if v >= k:
				geq.append(key)
			else:
				le.append(key)
		for num in geq:
			for j in range(k):
				ans[index[num][j]] = j + 1
		le_index = []
		for num in le:
			le_index.extend(index[num])
		m = len(le_index)
		idx = 1
		stop = m // k * k
		for i in range(m):
			if i == stop:
				break
			ans[le_index[i]] = idx
			idx += 1
			if idx == k + 1:
				idx = 1
		for i in ans:
			print(i, end=' ')
		print()
	return
main()


from collections import defaultdict

class Item:

	def __init__(self, value, index):
		self.value = value
		self.index = index

def colors(arr, k):
	indices = defaultdict(list)
	for (i, x) in enumerate(arr):
		indices[x].append(i)
	inverted = defaultdict(set)
	for x in arr:
		inverted[len(indices[x])].add(x)
	keys = sorted(inverted.keys())
	coloring_dict = defaultdict(list)
	color = 1
	for c in keys[::-1]:
		for x in inverted[c]:
			start_color = color
			for i in indices[x]:
				coloring_dict[color].append(i)
				color = color % k + 1
				if color == start_color:
					break
	coloring = ['0' for _ in arr]
	n = min([len(indices) for indices in coloring_dict.values()])
	for (color, indices) in coloring_dict.items():
		for i in indices[:n]:
			coloring[i] = str(color)
	return coloring

def main():
	outputs = []
	N = int(input())
	for _ in range(N):
		(_, k) = map(int, input().split())
		arr = list(map(int, input().split()))
		coloring = colors(arr, k)
		outputs.append(' '.join(coloring))
	print('\n'.join(outputs))
main()


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

def solve():
	(n, k) = getint()
	a = getint()
	ans = []
	cnt = [0] * (n + 1)
	for (i, x) in enumerate(a):
		if cnt[x] < k:
			ans.append((x, i))
		cnt[x] += 1
	ans.sort()
	cc = 0
	color = [0] * n
	m = len(ans) - len(ans) % k
	for (x, i) in ans[:m]:
		color[i] = cc + 1
		cc = (cc + 1) % k
	print(*color)
for _ in range(int(input())):
	solve()


import collections
import decimal
import math
t = int(input())
for w in range(t):
	(n, k) = [int(x) for x in input().split()]
	a = [int(x) for x in input().split()]
	v = [0 for i in range(n)]
	dic = {}
	for i in range(len(a)):
		if a[i] not in dic:
			dic.update({a[i]: [i]})
		else:
			dic[a[i]].append(i)
	s = 0
	for i in dic:
		s += min(k, len(dic[i]))
		while len(dic[i]) > k:
			dic[i].pop()
	s = s // k * k
	j = 1
	i = 0
	while i < s:
		for l in dic:
			val = dic[l].pop()
			v[val] = j
			j += 1
			if j > k:
				j = 1
			if len(dic[l]) == 0:
				dic.pop(l)
			break
		i += 1
	print(*v)


def find_colors(arr, k):
	answer = [0 for i in range(arr.__len__())]
	ocr = dict()
	for i in range(arr.__len__()):
		if arr[i] in ocr:
			ocr[arr[i]].append(i)
		else:
			ocr[arr[i]] = [i]
	ocrk = dict()
	ocr_ = dict()
	s = 0
	for i in ocr:
		if ocr[i].__len__() >= k:
			ocrk[i] = ocr[i]
		else:
			ocr_[i] = ocr[i]
			s += ocr_[i].__len__()
	for i in ocrk:
		paint = k
		for j in range(k, 0, -1):
			index = ocrk[i][k - j]
			answer[index] = j
	index_arr = []
	for i in ocr_:
		index_arr += ocr_[i]
	for i in range(s - s % k):
		index = index_arr[i]
		answer[index] = k - i % k
	return answer

def main():
	answers = []
	n = int(input())
	for i in range(n):
		(l, k) = map(int, input().split())
		arr = input().split()
		answers.append(find_colors(arr, k))
	for i in answers:
		print(*i)
main()


for _ in range(int(input())):
	(n, k) = map(int, input().split(' '))
	arr = list(map(int, input().split(' ')))
	dt = {}
	temp = []
	for x in range(n):
		if arr[x] in dt:
			dt[arr[x]] += 1
		else:
			dt[arr[x]] = 1
		if dt[arr[x]] <= k:
			temp.append([arr[x], x])
	for x in range(len(temp) % k):
		temp.pop()
	temp.sort()
	all = [0 for x in range(n)]
	idx = 1
	for x in temp:
		all[x[1]] = idx
		idx += 1
		if idx == k + 1:
			idx = 1
	for x in all:
		print(x, end=' ')
	print()


_ = int(input())
for __ in range(_):
	(n, k) = map(int, input().split())
	arr = list(map(int, input().split()))
	out = [0] * n
	d = {}
	d_bigger = {}
	d_pos = {}
	curr_col = 1
	for x in range(0, n):
		if arr[x] not in d:
			d[arr[x]] = 1
			d_pos[arr[x]] = [x]
		else:
			d[arr[x]] += 1
			d_pos[arr[x]].append(x)
	tot_num = 0
	for x in d:
		if d[x] < k:
			tot_num += d[x]
	m = tot_num // k
	tot_num = m * k
	for x in d_pos:
		if d[x] >= k:
			pos = d_pos[x]
			for y in range(k):
				out[pos[y]] = y + 1
		else:
			pos = d_pos[x]
			for y in pos:
				if tot_num:
					out[y] = curr_col
					curr_col += 1
					if curr_col > k:
						curr_col = 1
					tot_num -= 1
				else:
					out[y] = 0
	print(' '.join([str(x) for x in out]))


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

def S():
	return input()

def I():
	return int(S())

def M():
	return map(int, S().split())

def L():
	return list(M())
t = int(input())
for p in range(t):
	(n, k) = M()
	l = L()
	d = defaultdict(list)
	ans = [0] * n
	for i in range(n):
		d[l[i]].append(i)
	for i in d:
		d[i] = d[i][:k]
	z = 1
	k_freq = [0] * (k + 1)
	for i in d:
		for j in d[i]:
			ans[j] = z
			k_freq[z] += 1
			z += 1
			if z > k:
				z = 1
	mini = min(k_freq[1:])
	maxi = max(k_freq)
	if mini == maxi:
		print(*ans)
	else:
		for i in range(k + 1):
			if k_freq[i] > mini:
				diff = k_freq[i] - mini
				j = 0
				while j < n and diff > 0:
					if ans[j] == i:
						ans[j] = 0
						diff -= 1
					j += 1
		print(*ans)


import sys
input = lambda : sys.stdin.readline().rstrip()
from collections import defaultdict, deque, Counter
from functools import cmp_to_key
from heapq import *
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = [*map(int, input().split())]
	d = defaultdict(list)
	for (i, v) in enumerate(a):
		d[v].append(i)
	ans = [0] * n
	if k == 1:
		for i in d:
			ans[d[i].pop()] = 1
		print(*ans)
		continue
	if len(d) == 1:
		for (i, b) in d.items():
			for j in range(min(len(b), k)):
				ans[b[j]] = j + 1
		print(*ans)
		continue
	e = defaultdict(list)
	pq = [[0, i] for i in range(1, k + 1)]
	heapify(pq)
	for (i, b) in d.items():
		for j in range(min(len(b), k)):
			(ct, clr) = heappop(pq)
			ct += 1
			ans[b[j]] = clr
			heappush(pq, [ct, clr])
			e[clr].append(b[j])
	(mn, clr) = heappop(pq)
	aa = list(e.items())
	for (i, b) in aa:
		while len(b) > mn:
			ans[b.pop()] = 0
	print(*ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	l = list(map(int, input().split()))
	l1 = [0] * n
	l2 = []
	l3 = []
	d = {}
	for (x, y) in enumerate(l):
		if y not in d:
			d[y] = [x]
		elif len(d[y]) >= k:
			continue
		else:
			d[y] += [x]
	for x in d.values():
		if len(x) < k:
			l2.extend(x)
		else:
			l3.append(x)
	var = 1
	for x in range(len(l2) // k * k):
		l1[l2[x]] = var
		var += 1
		if var > k:
			var = 1
	for x in range(len(l3)):
		var = 1
		for y in range(k):
			l1[l3[x][y]] = var
			var += 1
	print(*l1)


from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
import os, sys
input = lambda : sys.stdin.buffer.readline().rstrip(b'\r\n')

def dbp(*args, **kwargs):
	print(*args, file=sys.stderr, **kwargs)
a_str = lambda : input().decode('ascii')
get_int_list = lambda : [int(x) for x in input().split()]
join_str = lambda l, ch=' ': ch.join((str(x) for x in l))

def IR_SO_DUMN(s, k=2):
	d = defaultdict(list)
	for (idx, ch) in enumerate(s):
		d[ch].append(idx)
	ans = [0] * len(s)
	ccol = best = 0
	for (ch, il) in d.items():
		used = set()
		for idx in il:
			used.add(ccol)
			ans[idx] = ccol + 1
			ccol = ccol + 1
			if ccol == k:
				best += 1
				ccol = 0
			if ccol in used:
				break
	c = Counter()
	for (idx, a) in enumerate(ans):
		c[a] += 1
		if c[a] > best:
			ans[idx] = 0
	return join_str(ans)

def do_thing():
	(n, k) = get_int_list()
	s = get_int_list()
	return IR_SO_DUMN(s, k)

def multicase():
	maxcc = int(input().strip())
	for cc in range(maxcc):
		print(do_thing())
multicase()


from sys import stdin, stdout
from collections import defaultdict
t = int(stdin.readline().strip())
for _ in range(t):
	(n, k) = list(map(int, stdin.readline().split()))
	arr = list(map(int, stdin.readline().split()))
	freq = dict()
	color = dict()
	for i in arr:
		if i in freq:
			freq[i] += 1
		else:
			freq[i] = 1
		if freq[i] >= k:
			color[i] = k
	final = [0 for x in range(n)]
	remainCount = 0
	remain = defaultdict(list)
	for i in range(n):
		if arr[i] in color:
			final[i] = color[arr[i]]
			color[arr[i]] = max(0, color[arr[i]] - 1)
			continue
		remain[arr[i]].append(i)
		remainCount += 1
	tempArr = []
	for x in remain:
		for z in remain[x]:
			tempArr.append(z)
	curColor = 1
	for i in range(len(tempArr)):
		if curColor > k:
			curColor = 1
		if k - curColor + i < len(tempArr):
			index = tempArr[i]
			final[index] = curColor
			curColor += 1
		else:
			break
	print(*final)


import sys, io, os, math, bisect, heapq
from collections import Counter, deque, defaultdict

def solve():
	(n, k) = [int(o) for o in input().split()]
	a = list(map(int, input().split()))[:n]
	d = defaultdict(list)
	ans = [0] * n
	b = []
	x = 1
	for i in range(n):
		d[a[i]].append(i)
	for i in d:
		for j in range(min(len(d[i]), k)):
			b.append(d[i][j])
	while len(b) % k != 0:
		b.pop()
	for i in range(len(b)):
		ans[b[i]] = i % k + 1
	print(*ans)
for _ in range(int(input())):
	solve()


import sys
input = sys.stdin.readline

def solve():
	(n, k) = map(int, input().split())
	c = [[] for i in range(n + 1)]
	a = list(map(int, input().split()))
	z = 0
	for i in range(n):
		if len(c[a[i]]) < k:
			c[a[i]].append(i)
			z += 1
	b = z // k
	d = b * k
	r = [0] * n
	j = 0
	for v in c:
		for w in v:
			r[w] = j % k + 1
			j += 1
			if j == d:
				print(' '.join(map(str, r)))
				return
	print(' '.join(map(str, r)))
for i in range(int(input())):
	solve()


import functools
import itertools
import math
import random
import string
from collections import defaultdict, Counter
from heapq import *
from bisect import bisect_left, bisect_right

def repeat(_func=None, *, times=1):

	def decorator(func):

		@functools.wraps(func)
		def wrapper(*args, **kwargs):
			for _ in range(times):
				func(*args, **kwargs)
		return wrapper
	if _func is None:
		return decorator
	else:
		return decorator(_func)

def unpack(func=int):
	return map(func, input().split())

def l_unpack(func=int):
	return list(map(func, input().split()))

def getint():
	return int(input())

def getmatrix(rows):
	return [list(map(int, input().split())) for _ in range(rows)]

def display_matrix(mat):
	for i in range(len(mat)):
		print(mat[i])
	print('-' * 20)
MOD = 1000000007

@repeat(times=int(input()))
def main():

	def chain():
		for v in hmap.values():
			yield from v
	(n, k) = unpack()
	arr = l_unpack()
	out = [0] * n
	if k == 0:
		print(*out)
		return
	total = 0
	hmap = defaultdict(list)
	for (i, c) in enumerate(arr):
		if len(hmap[c]) < k:
			hmap[c].append(i)
			total += 1
	each = total // k
	color = [(0, i) for i in range(1, k + 1)]
	for pos in chain():
		while color and color[0][0] == each:
			heappop(color)
		if not total or not color:
			break
		(val, col) = color[0]
		out[pos] = col
		total -= 1
		heapreplace(color, (val + 1, col))
	print(*out)
main()


from collections import *
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = list(map(int, input().split()))
	p = defaultdict(list)
	for (i, x) in enumerate(s):
		p[x].append([i, 0])
	c = Counter(s)
	ans = 0
	curr = 0
	h = []
	for (x, v) in c.items():
		if v >= k:
			for i in range(k):
				p[x][i][1] = i + 1
		else:
			for i in range(v):
				p[x][i][1] = curr + 1
				h.append((x, i))
				curr += 1
				if curr == k:
					curr = 0
	for _ in range(curr):
		(x, i) = h.pop()
		p[x][i][1] = 0
	ans = [None for _ in range(n)]
	for (_, v) in p.items():
		for el in v:
			c = el[1]
			ans[el[0]] = c
	print(*ans)


t = int(input())
for _ in range(t):
	(n, k) = list(map(int, input().rstrip().split()))
	arr = list(map(int, input().rstrip().split()))
	d = {}
	d2 = {}
	for i in range(n):
		if arr[i] in d.keys():
			d[arr[i]] += 1
		else:
			d[arr[i]] = 1
	final = [-1] * n
	for i in range(n):
		if d[arr[i]] >= k:
			if arr[i] in d2.keys():
				final[i] = d2[arr[i]] + 1
				d2[arr[i]] += 1
			else:
				final[i] = 1
				d2[arr[i]] = 1
	d = {}
	c = 0
	for i in range(n):
		if final[i] == -1:
			c += 1
			if arr[i] in d.keys():
				d[arr[i]].append(i)
			else:
				d[arr[i]] = [i]
	e = 0
	curr = 0
	for i in d.keys():
		if e == k * (c // k):
			break
		for j in d[i]:
			final[j] = curr + 1
			curr += 1
			curr = curr % k
			e += 1
			if e == k * (c // k):
				break
	for i in range(n):
		if final[i] > k or final[i] == -1:
			final[i] = 0
	print(*final)


import sys
import bisect
from bisect import bisect_left as lb
from bisect import bisect_right as rb
input_ = lambda : sys.stdin.readline().strip('\r\n')
from math import log
from math import gcd
from math import atan2, acos
from random import randint
sa = lambda : input_()
sb = lambda : int(input_())
sc = lambda : input_().split()
sd = lambda : list(map(int, input_().split()))
sflo = lambda : list(map(float, input_().split()))
se = lambda : float(input_())
sf = lambda : list(input_())
flsh = lambda : sys.stdout.flush()
mod = 10 ** 9 + 7
mod1 = 998244353
gp = []
cost = []
dp = []
mx = []
ans1 = []
ans2 = []
special = []
specnode = []
a = 0
kthpar = []

def dfs2(root, par):
	if par != -1:
		dp[root] = dp[par] + 1
	for i in range(1, 20):
		if kthpar[root][i - 1] != -1:
			kthpar[root][i] = kthpar[kthpar[root][i - 1]][i - 1]
	for child in gp[root]:
		if child == par:
			continue
		kthpar[child][0] = root
		dfs(child, root)
ans = 0
b = []
vis = []
tot = 0
time = []
time1 = []
adj = []
mx = -1

def dfs(a, b, p, c):
	if a == b:
		return c
	for (i, j) in adj[a]:
		if i == p:
			continue
		temp = dfs(i, b, a, c + j)
		if dfs(i, b, a):
			mx = max(i, mx)
			return 1
eps = 9e-07

def hnbhai(tc):
	(n, k) = sd()
	s = sd()
	d = {}
	for i in s:
		d[i] = d.get(i, 0) + 1
	store = {}
	for i in range(n):
		if store.get(s[i]) is None:
			store[s[i]] = [i]
		else:
			store[s[i]].append(i)
	temp = []
	ans = [0] * n
	for i in store:
		t = store[i]
		t = [len(t)] + t
		temp.append(t)
	temp.sort(reverse=True)
	abe = []
	tt = 1
	for i in range(len(temp)):
		t = temp[i][1:]
		tot = 0
		for j in t:
			abe.append([j, tt])
			if len(abe) == k:
				for a in abe:
					ans[a[0]] = a[1]
				abe = []
			tt += 1
			tot += 1
			if tt > k:
				tt = 1
			if tot == k:
				break
	print(*ans)

def dfs(root):
	global tot, vis, gp
	for child in gp[root]:
		if vis[child] == 0:
			tot += 1
			vis[child] = 1
			dfs(child)
for _ in range(sb()):
	hnbhai(_ + 1)


from collections import Counter, defaultdict

def solve():
	(n, k) = map(int, input().split())
	s = list(map(int, input().split()))
	pos = defaultdict(list)
	c = defaultdict(int)
	for (i, x) in enumerate(s):
		pos[x].append(i)
		c[x] += 1
	ans = [0] * n
	posleft = []
	c_left = 0
	for key in pos:
		if c[key] >= k:
			for i in range(k):
				ans[pos[key][i]] = 1 + i
		else:
			posleft.extend(pos[key])
			c_left += c[key]
	left = c_left // k * k
	for i in range(left):
		ans[posleft[i]] = i % k + 1
	print(*ans)
tests = int(input())
for _ in range(tests):
	solve()


from collections import defaultdict as dd

def findColors():
	t = int(input())
	while t != 0:
		t = t - 1
		(n, k) = map(int, input().split())
		d = list(map(int, input().split()))
		def_dic = dd(list)
		for i in range(n):
			def_dic[d[i]].append(i)
		ans_arr = [0] * n
		residue = []
		for i in def_dic:
			if len(def_dic[i]) >= k:
				for m in range(k):
					ans_arr[def_dic[i][m]] = m + 1
			else:
				residue += def_dic[i]
		ll = len(residue) // k * k
		for i in range(ll):
			ans_arr[residue[i]] = i % k + 1
		print(*ans_arr)
findColors()


for _ in range(int(input())):
	(n, k) = list(map(int, input().split()))
	arr = list(map(int, input().split()))
	mapper = {}
	for i in range(n):
		if arr[i] in mapper:
			mapper[arr[i]].append(i)
		else:
			mapper[arr[i]] = [i]
	ans = [0 for i in range(n)]
	rem = []
	for i in mapper:
		l = len(mapper[i])
		if l >= k:
			for j in range(k):
				ans[mapper[i][j]] = j + 1
		else:
			rem += mapper[i]
	l = len(rem)
	f = l // k
	for j in range(f * k):
		ans[rem[j]] = j % k + 1
	print(*ans)


GI = lambda : int(input())
GIS = lambda : map(int, input().split())
LGIS = lambda : list(GIS())
from collections import Counter

def main():
	for _ in range(GI()):
		(n, k) = GIS()
		xs = LGIS()
		ctr = Counter(xs)
		nums_to_colors = {}
		cc = 0
		for (x, c) in ctr.most_common():
			colors = nums_to_colors.setdefault(x, [])
			for i in range(min(c, k)):
				colors.append(cc + 1)
				cc = (cc + 1) % k
		while cc:
			for (num, colors) in nums_to_colors.items():
				while colors and colors[-1] == cc:
					colors.pop()
					cc -= 1
					if not cc:
						break
				if not cc:
					break
		colors = [0] * n
		for (i, x) in enumerate(xs):
			colors[i] = nums_to_colors[x].pop() if nums_to_colors[x] else 0
		print(' '.join(map(str, colors)))
main()


t = int(input())
for t1 in range(t):
	(n, k) = input().split(' ')
	(n, k) = (int(n), int(k))
	s = input().split(' ')
	s = [int(x) for x in s]
	m = dict()
	for i in range(len(s)):
		if s[i] in m.keys():
			m[s[i]] += 1
		else:
			m[s[i]] = 1
	d = dict()
	e = dict()
	count = 0
	for ele in m.keys():
		if m[ele] >= k:
			d[ele] = 1
		else:
			e[ele] = 1
			count += m[ele]
	flag = count // k
	s1 = [-1] * n
	for i in range(len(s)):
		if s[i] in d.keys():
			if d[s[i]] > k:
				s1[i] = 0
			else:
				d[s[i]] += 1
				s1[i] = d[s[i]] - 1
		else:
			pass
	e1 = dict()
	for i in range(len(s)):
		if s[i] in e.keys():
			if s[i] in e1.keys():
				e1[s[i]].append(i)
			else:
				e1[s[i]] = [i]
	counter = 1
	f = 1
	for i in e1.keys():
		for j in e1[i]:
			if f <= flag:
				s1[j] = counter
				counter += 1
				if counter == k + 1:
					counter = 1
					f += 1
			else:
				s1[j] = 0
	for ele in s1:
		print(ele, end=' ')
	print('\n')


def u():
	return map(int, input().split())
for _ in range(int(input())):
	(n, k) = u()
	l = list(u())
	lnew = [[l[i], i, 0] for i in range(n)]
	lnew = sorted(lnew, key=lambda x: x[0])
	arr = [0] * (k + 1)
	cw = 1
	m = dict()
	for el in lnew:
		if el[0] not in m:
			m[el[0]] = 0
		if m[el[0]] >= k:
			pass
		else:
			el[2] = cw
			arr[cw] += 1
			cw += 1
			m[el[0]] += 1
			if cw == k + 1:
				cw = 1
	mark = 0
	for i in range(1, k):
		if arr[i] != arr[i + 1]:
			mark = i
			break
	s = set()
	for i in range(1, mark + 1):
		s.add(i)
	for el in lnew:
		if el[2] in s:
			s.remove(el[2])
			el[2] = 0
	lnew = sorted(lnew, key=lambda x: x[1])
	ans = list()
	for el in lnew:
		ans.append(el[2])
	print(*ans)


T = int(input())
while T > 0:
	T -= 1
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	indices = {}
	p = [0] * n
	sb = 0
	for i in range(n):
		if a[i] not in indices:
			indices[a[i]] = []
		if len(indices[a[i]]) == k:
			continue
		indices[a[i]].append(i)
		sb += 1
	sb -= sb % k
	for idx in indices:
		for i in indices[idx]:
			p[i] = sb % k + 1
			sb -= 1
			if sb == 0:
				break
		if sb == 0:
			break
	print(' '.join(map(str, p)))


import sys
input = sys.stdin.readline
from collections import Counter, defaultdict
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	A = list(map(int, input().split()))
	cnt = Counter(A)
	dic = defaultdict(list)
	rem = []
	for (i, a) in enumerate(A):
		dic[a].append(i)
	tot = 0
	cand = []
	for (x, v) in dic.items():
		rem += v[k:]
		dic[x] = v[:k]
		tot += len(dic[x])
		cand += dic[x]
	group = tot // k
	ans = [0] * n
	for i in range(group * k):
		ans[cand[i]] = i % k + 1
	print(*ans)


t = int(input())
for _ in range(t):
	from collections import Counter
	(n, k) = tuple(map(int, input().split()))
	arr = list(map(int, input().split()))
	ans = [0] * n
	y = {}
	d = {}
	for (i, x) in enumerate(arr):
		if x in d:
			if d[x] < k:
				y[x].append(i)
				d[x] += 1
		elif k > 0:
			y[x] = [i]
			d[x] = 1
	a = sum(d.values())
	a -= a % k
	for r in y.values():
		for (i, j) in enumerate(r):
			ans[j] = 1 + a % k
			a -= 1
			if a == 0:
				break
		else:
			continue
		break
	print(' '.join(map(str, ans)))


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	arr = list(map(int, input().split()))
	di = {}
	for i in range(len(arr)):
		if arr[i] not in di:
			di[arr[i]] = [i]
		elif len(di[arr[i]]) < k:
			di[arr[i]].append(i)
	s = []
	for ar in di.values():
		for ind in ar:
			s.append(ind)
	r = len(s) // k * k
	ans = [0] * n
	for i in range(r):
		ans[s[i]] = i % k + 1
	print(*ans)


import sys
t = int(sys.stdin.readline())
for _ in range(t):
	(n, k) = map(int, sys.stdin.readline().split())
	se = list(map(int, sys.stdin.readline().split()))
	l = list(enumerate(se))
	seq = sorted(l, key=lambda x: x[1])
	p = [[] for _ in range(k)]
	j = 0
	for (i, a) in seq:
		if not p[j]:
			p[j].append((i, a))
			j = (j + 1) % k
		elif p[j][-1][1] != a:
			p[j].append((i, a))
			j = (j + 1) % k
	for m in range(k - 2, -1, -1):
		if len(p[m + 1]) != len(p[m]):
			p[m].pop()
	answer = [0 for _ in range(n)]
	for j in range(len(p)):
		for nums in p[j]:
			answer[nums[0]] = j + 1
	print(' '.join(map(str, answer)))


import sys
cin = int(sys.stdin.readline().strip())
for testcase in range(cin):
	cin1 = list(map(int, sys.stdin.readline().strip().split()))
	cin2 = list(map(int, sys.stdin.readline().strip().split()))
	(n, k) = (cin2, cin1[-1])
	d = {}
	for i in range(len(n)):
		if n[i] not in d:
			d[n[i]] = [i]
		else:
			d[n[i]].append(i)
	ans = [0 for i in range(len(n))]
	tt = []
	for i in d:
		if len(d[i]) >= k:
			for j in range(k):
				ans[d[i][j]] = j + 1
		else:
			for j in d[i]:
				tt.append(j)
	for j in range(len(tt) // k * k):
		ans[tt[j]] = j % k + 1
	for i in range(len(ans)):
		ans[i] = str(ans[i])
	print(' '.join(ans))


import sys
import math
from typing import DefaultDict
mod = 10 ** 9 + 7
LI = lambda : [int(k) for k in input().split()]
input = lambda : sys.stdin.readline().rstrip()
IN = lambda : int(input())
S = lambda : input()
r = range
for t in r(IN()):
	(n, k) = LI()
	li = LI()
	d = dict()
	ans = 0
	for ele in li:
		if ele not in d:
			d[ele] = 1
			ans += 1
		elif d[ele] < k:
			d[ele] += 1
			ans += 1
	col = ans // k
	ans = [0] * n
	indd = DefaultDict(list)
	for i in range(n):
		indd[li[i]] += [i]
	cl = 0
	tl = col * k
	cnt = 0
	for ele in indd:
		if cnt == tl:
			break
		lim = 0
		ele = list(indd[ele])
		for item in ele:
			if cnt == tl:
				break
			if lim == k:
				break
			ans[item] = cl % k + 1
			cl += 1
			cnt += 1
			lim += 1
	print(*ans)


import sys
from sys import stdout
input = lambda : sys.stdin.readline().strip()
P = lambda : list(map(int, input().split()))
from math import factorial as f, gcd
from collections import deque, defaultdict as dd, Counter as C
from heapq import heapify, heappop, heappush, heappushpop, heapreplace, merge
from random import randint, choice, sample
import time
mod = 10 ** 9 + 7
a = ord('a')

class FT:

	def __init__(self, N):
		self.ft = [0] * (N + 1)
		self.N = N

	def ls(self, x):
		return x & -x

	def fenwick_update(self, p, v):
		while p <= self.N:
			self.ft[p] += v
			p += self.ls(p)

	def fenwick_query(self, p):
		s = 0
		while p:
			s += self.ft[p]
			p -= self.ls(p)
		return s
start = time.time()

def fast_exp(x, exp):
	ans = 1
	base = x
	while exp:
		if exp & 1:
			ans *= base
		base *= base
		base %= mod
		ans %= mod
		exp >>= 1
	return ans

def countBits(n):
	count = 0
	while n:
		count += n & 1
		n >>= 1
	return count

def submasks(n):
	org = n
	while n:
		yield n
		n = n - 1 & org

def solve():
	(n, k) = P()
	L = P()
	c = list(C(L).items())
	c.sort(key=lambda i: -i[1])
	c2 = dd(list)
	for (i, x) in enumerate(L):
		c2[x].append(i)
	ans = [0] * n
	curr = 1
	s = []
	co = 0
	for (kk, v) in c:
		v = min(v, k)
		for i in range(v):
			topaint = c2[kk][i]
			ans[topaint] = curr
			curr += 1
			if curr == k + 1:
				curr = 1
			s.append(topaint)
			co += 1
	for _ in range(co % k):
		ans[s.pop()] = 0
	print(*ans)
tc = int(input())
for t in range(1, tc + 1):
	solve()


import os
import sys
from collections import defaultdict
from io import BytesIO, IOBase
_str = str
str = lambda x=b'': x if type(x) is bytes else _str(x).encode()
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')
from collections import Counter

def f(a, k):
	ind = defaultdict(list)
	for i in range(len(a)):
		ind[a[i]].append(i)
	color = [0] * len(a)
	temp = 1
	for i in ind:
		for j in range(min(len(ind[i]), k)):
			color[ind[i][j]] = temp
			temp += 1
			if temp > k:
				temp = 1
	cnt = Counter(color)
	mn = float('inf')
	for i in range(1, k + 1):
		mn = min(mn, cnt[i])
	for i in range(len(color)):
		if cnt[color[i]] > mn:
			cnt[color[i]] -= 1
			color[i] = 0
	return color
for i in range(int(input())):
	(n, k) = map(int, input().strip().split())
	l = list(map(int, input().strip().split()))
	print(*f(l, k))


t = int(input())
while t > 0:
	t -= 1
	a = input().split()
	n = int(a[0])
	k = int(a[1])
	a = input().split()
	a = [int(x) for x in a]
	li = []
	ans = []
	le = 0
	for x in range(n):
		li.append([])
		ans.append(0)
	for i in range(n):
		va = li[a[i] - 1]
		va.append(i)
		if len(va) <= k:
			le += 1
	ki = k
	le = le // k * k
	for i in range(n):
		va = li[i]
		if len(va) >= k:
			for ii in range(k):
				ans[va[ii]] = ii + 1
			li[i] = []
			le -= k
	rk = 1
	for i in range(n):
		va = li[i]
		if len(va) > 0:
			for xx in va:
				if le > 0:
					ans[xx] = rk
					rk = rk % k + 1
					le -= 1
	ans = [str(x) for x in ans]
	ans = ' '.join(ans)
	print(ans)


from sys import stdin
from collections import defaultdict
input = stdin.readline
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	d = defaultdict(lambda : [])
	for i in range(n):
		d[a[i]].append(i)
	b = []
	s = 0
	for i in d:
		b.append([len(d[i]), d[i]])
		s += min(len(d[i]), k)
	b.sort(reverse=True)
	c = k * (s // k)
	ans = [0] * n
	b = [i[1][:k] for i in b]
	m = 0
	for ai in b:
		for j in ai:
			if m >= c:
				break
			ans[j] = m % k + 1
			m += 1
	print(*ans)


from collections import Counter

def wonderfulcoloring(n, k):
	tempSol = []
	solution = []
	numDict = {}
	counters = Counter(k)
	colorNum = 0
	for (num, count) in counters.items():
		numDict[num] = [colorNum, min(count + colorNum, n + colorNum)]
		colorNum += min(count, n)
		if colorNum > n:
			colorNum = colorNum % n
			tempSol = []
			tempSol.append(num)
		elif colorNum == n:
			colorNum = colorNum % n
			tempSol = []
		else:
			tempSol.append(num)
	if tempSol:
		for num in tempSol:
			if numDict[num][0] <= n <= numDict[num][1]:
				numDict[num][1] = n
			else:
				numDict[num] = [0, 0]
	for num in k:
		color = numDict[num][0]
		if color >= numDict[num][1]:
			solution.append(0)
		else:
			solution.append(color % n + 1)
			numDict[num][0] += 1
	solution = [str(x) for x in solution]
	print(' '.join(solution))
t = int(input())
for i in range(t):
	(n, k) = [int(x) for x in input().split()]
	sequence = [int(x) for x in input().split()]
	wonderfulcoloring(k, sequence)


T = int(input())
for t in range(T):
	(n, k) = map(int, input().split())
	A = [int(x) for x in input().split()]
	M = {}
	for (i, a) in enumerate(A):
		if a not in M:
			M[a] = []
		if len(M[a]) < k:
			M[a].append(i)
	m = 0
	m = sum([len(M[e]) for e in M])
	m -= m % k
	color = 0
	sol = [str(0)] * n
	for e in M:
		for i in M[e]:
			color += 1
			sol[i] = str(color)
			color %= k
			m -= 1
			if m == 0:
				break
		if m == 0:
			break
	print(' '.join(sol))


t = int(input())
results = []
for i in range(t):
	(n, k) = map(int, input().split())
	s = [(int(c), j) for (j, c) in enumerate(input().split())]
	s.sort(key=lambda x: x[0])
	counts = {}
	for (c, j) in s:
		counts[c] = counts.get(c, 0) + 1
	new_counts = {}
	total = 0
	for c in counts:
		if counts[c] <= k:
			new_counts[c] = 'reg'
			total += counts[c]
		else:
			new_counts[c] = k
	total //= k
	total *= k
	seq = [0] * n
	current = 1
	for (c, j) in s:
		if new_counts[c] == 'reg':
			if total > 0:
				seq[j] = current
				current = current % k + 1
				total -= 1
			else:
				seq[j] = 0
		elif new_counts[c] > 0:
			seq[j] = new_counts[c]
			new_counts[c] -= 1
		else:
			seq[j] = 0
	results.append(' '.join([str(num) for num in seq]))
for i in range(t):
	print(results[i])


def solve(n, k, arr):
	store = {}
	final = [0 for i in range(n)]
	for (i, ele) in enumerate(arr):
		if ele not in store:
			store[ele] = [i]
		else:
			store[ele].append(i)
	rem = []
	for ele in store:
		length = len(store[ele])
		if length >= k:
			current = 1
			for i in range(k):
				final[store[ele][i]] = current
				current += 1
		else:
			present = len(rem)
			req = k - present
			if length <= req:
				rem.extend(store[ele])
				newArr = []
			else:
				newArr = store[ele][req:]
				rem.extend(store[ele][:req])
			if len(rem) == k:
				current = 1
				for j in rem:
					final[j] = current
					current += 1
				rem = newArr
	if len(rem) == k:
		current = 1
		for j in rem:
			final[j] = current
			current += 1
	print(*final)
	return
T = int(input())
while T:
	(n, k) = [int(x) for x in input().split()]
	arr = [int(x) for x in input().split()]
	solve(n, k, arr)
	T -= 1


from collections import defaultdict
import sys, io, os
INP = sys.stdin.readline
inp = lambda : [*map(int, INP().encode().split())]
sinp = lambda : [*map(str, INP().split())]
out = sys.stdout.write

def main():
	for _ in range(inp()[0]):
		(n, k) = inp()
		d = defaultdict(int)
		check = defaultdict(list)
		l = inp()
		for i in range(n):
			if len(check[l[i]]) < k:
				check[l[i]].append(i)
		c = 0
		ans = [0] * n
		for i in check:
			c += len(check[i])
		r = c // k
		res = []
		m = k
		for i in range(r * k):
			res.append(m)
			m -= 1
			if m == 0:
				m = k
		coz = []
		for i in check:
			coz += check[i]
		for i in range(r * k):
			ans[coz[i]] = res[i]
		print(' '.join(map(str, ans)))

def SumOfExpOfFactors(a):
	fac = 0
	lis = SortedList()
	if not a & 1:
		lis.add(2)
	while not a & 1:
		a >>= 1
		fac += 1
	for i in range(3, int(a ** 0.5) + 1, 2):
		if not a % i:
			lis.add(i)
		while not a % i:
			a //= i
			fac += 1
	if a != 1:
		lis.add(a)
		fac += 1
	return (fac, lis)
div = [0] * 1000001

def NumOfDivisors(n):
	for i in range(1, n + 1):
		for j in range(i, n + 1, i):
			div[j] += 1

def primes1(n):
	sieve = [True] * (n // 2)
	for i in range(3, int(n ** 0.5) + 1, 2):
		if sieve[i // 2]:
			sieve[i * i // 2::i] = [False] * ((n - i * i - 1) // (2 * i) + 1)
	return [2] + [2 * i + 1 for i in range(1, n // 2) if sieve[i]]

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

class Graph:

	def __init__(self):
		self.Graph = defaultdict(list)

	def addEdge(self, u, v):
		self.Graph[u].append(v)
		self.Graph[v].append(u)

	def DFSUtil(self, v, visited):
		visited.add(v)
		for neighbour in self.Graph[v]:
			if neighbour not in visited:
				self.DFSUtil(neighbour, visited)

	def DFS(self, v):
		visited = set()
		self.DFSUtil(v, visited)

	def BFS(self, s):
		visited = set()
		queue = []
		queue.append(s)
		visited.add(s)
		while queue:
			s = queue.pop(0)
			for i in self.Graph[s]:
				if i not in visited:
					queue.append(i)
					visited.add(i)

class SortedList:

	def __init__(self, iterable=[], _load=200):
		values = sorted(iterable)
		self._len = _len = len(values)
		self._load = _load
		self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
		self._list_lens = [len(_list) for _list in _lists]
		self._mins = [_list[0] for _list in _lists]
		self._fen_tree = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for i in range(len(_fen_tree)):
			if i | i + 1 < len(_fen_tree):
				_fen_tree[i | i + 1] += _fen_tree[i]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len -= 1
		self._fen_update(pos, -1)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len += 1
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				_lists.insert(pos + 1, _list[_load:])
				_list_lens.insert(pos + 1, len(_list) - _load)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = _load
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))
main()


def Solve():
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	dic = {}
	for i in a:
		if dic.get(i) == None:
			dic[i] = 1
		else:
			dic[i] += 1
	lst = list(dic.values())
	b = [0 for i in a]
	dic2 = {}
	s = 0
	for i in range(len(a)):
		if dic[a[i]] >= k:
			if dic2.get(a[i]) == None:
				b[i] = k
				dic2[a[i]] = k - 1
			else:
				b[i] = dic2[a[i]]
				if dic2[a[i]] > 0:
					dic2[a[i]] -= 1
		else:
			s += 1
	dic3 = {}
	for i in range(len(a)):
		if dic[a[i]] < k:
			if dic3.get(a[i]) == None:
				dic3[a[i]] = [i]
			else:
				dic3[a[i]].append(i)
	lst = list(dic3.values())
	p = k
	r = 1
	for i in range(len(lst)):
		for j in range(len(lst[i])):
			if r * k <= s:
				b[lst[i][j]] = p
				p -= 1
				if p == 0:
					p = k
					r += 1
			else:
				b[lst[i][j]] = 0
	for i in b:
		print(i, end=' ')
	print()
q = int(input())
while q > 0:
	Solve()
	q -= 1


def func(n, k, a):
	m = [0 for i in range(n + 1)]
	sm = [[] for i in range(n + 1)]
	res = [0 for i in range(n)]
	for i in range(n):
		m[a[i]] += 1
		sm[a[i]].append(i)
	extra = 0
	c = 0
	res = [0 for i in range(n)]
	for i in range(n + 1):
		if m[i] >= k:
			extra += m[i] - k
			c += 1
			for j in range(k):
				res[sm[i][j]] = j + 1
	vvv = (n - c * k - extra) // k
	c = 0
	x = 1
	for i in range(n + 1):
		if m[i] < k:
			if c == vvv * k:
				return res
			for j in range(len(sm[i])):
				res[sm[i][j]] = x
				c += 1
				x += 1
				if x == k + 1:
					x = 1
				if c == vvv * k:
					return res
	return res
for q in range(int(input())):
	(n, k) = list(map(int, input().split()))
	a = list(map(int, input().split()))
	print(*func(n, k, a))


from math import *
from collections import *
from functools import *
from bisect import *
from itertools import *
from heapq import *
import sys
inf = float('inf')
ninf = -float('inf')
ip = sys.stdin.readline
alphal = 'abcdefghijklmnopqrstuvwxyz'
alphau = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
mod = 10 ** 9 + 7

def ipl():
	return list(map(int, ip().split()))

def ipn():
	return int(ip())

def ipf():
	return float(ip())

def solve():
	(n, k) = ipl()
	a = ipl()
	c = defaultdict(int)
	d = 0
	l = []
	for (_, i) in enumerate(a):
		if c[i] < k:
			l.append((a[_], _))
		c[i] += 1
	r = [0] * n
	l.sort()
	t = 1
	ra = len(l) - len(l) % k
	for (_, v) in l[:ra]:
		r[v] = t % k + 1
		t += 1
	print(*r)
t = ipn()
for _ in range(t):
	solve()


for nt in range(int(input())):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	b = [[] for i in range(n)]
	count = 0
	for i in range(n):
		if len(b[a[i] - 1]) < k:
			b[a[i] - 1].append(i)
			count += 1
	total = count - count % k
	ans = [0] * n
	curr = 1
	count = 0
	flag = False
	for i in b:
		for j in i:
			ans[j] = curr
			curr += 1
			if curr > k:
				curr = 1
			count += 1
			if count == total:
				flag = True
				break
		if flag:
			break
	print(*ans)


import heapq
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = list(map(int, input().split()))
	cnt = [[] for _ in range(n + 1)]
	ans = [0] * len(s)
	heap = [(0, i) for i in range(1, k + 1)]
	for (i, char) in enumerate(s):
		cnt[char].append(i)
	colorind = [[] for _ in range(k + 1)]
	for i in range(n + 1):
		j = 0
		while len(cnt[i]) > 0 and j < k:
			j += 1
			(ct, color) = heapq.heappop(heap)
			ind = cnt[i].pop()
			colorind[color].append(ind)
			ans[ind] = color
			heapq.heappush(heap, (ct + 1, color))
	minval = 10000000
	for (ct, color) in heap:
		minval = min(minval, ct)
	for i in range(len(colorind)):
		while len(colorind[i]) > minval:
			ind = colorind[i].pop()
			ans[ind] = 0
	for a in ans:
		print('{}'.format(a), end=' ')
	print()


import os.path
from math import gcd, floor, ceil
from collections import *
import sys
mod = 1000000007
INF = float('inf')

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

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

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

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

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

def prl(n):
	return sys.stdout.write(str(n) + ' ')
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def solve():
	(n, k) = mp()
	l = li()
	d = Counter(l)
	ind = defaultdict(list)
	for (i, ele) in enumerate(l):
		ind[ele].append(i)
	found = set()
	odds = 0
	not_found = set()
	for i in d:
		if d[i] >= k:
			found.add(i)
		else:
			not_found.add(i)
			odds += d[i]
	ans = [0] * n
	for i in found:
		count = 0
		for j in ind[i]:
			ans[j] = count + 1
			count += 1
			if count == k:
				break
	round = 0
	count = 0
	for i in not_found:
		for j in ind[i]:
			if count == k:
				count = 0
				round += 1
			if round >= odds // k:
				break
			ans[j] = count + 1
			count += 1
	print(*ans)
for _ in range(inp()):
	solve()


import heapq
import sys
from math import *
import threading
from heapq import *
from itertools import count
from pprint import pprint
from collections import defaultdict
from heapq import heapify, heappop, heappush
mod = 10 ** 9 + 7
inf = 10 ** 15
decision = ['NO', 'YES']
yes = 'YES'
no = 'NO'
import os
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

	def npr(self, n, k):
		if k < 0 or n < k:
			return 0
		f = self.factorial
		return f.calc(n) * f.invFactorial(n - k) % self.MOD

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

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

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

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

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

def pref(li):
	pref_sum = [0]
	for i in li:
		pref_sum.append(pref_sum[-1] + i)
	return pref_sum

def SieveOfEratosthenes(n):
	prime = [{1, i} for i in range(n + 1)]
	p = 2
	while p <= n:
		for i in range(p * 2, n + 1, p):
			prime[i].add(p)
		p += 1
	return prime

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

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

def sumk(a, b):
	print('called for', a, b)
	ans = a * (a + 1) // 2
	ans -= b * (b + 1) // 2
	return ans

def sumi(n):
	ans = 0
	if len(n) > 1:
		for x in n:
			ans += int(x)
		return ans
	else:
		return int(n)

def checkwin(x, a):
	if a[0][0] == a[1][1] == a[2][2] == x:
		return 1
	if a[0][2] == a[1][1] == a[2][0] == x:
		return 1
	if len(set(a[0])) == 1 and a[0][0] == x or (len(set(a[1])) == 1 and a[1][0] == x) or (len(set(a[2])) == 1 and a[2][0] == x):
		return 1
	if len(set(a[0][:])) == 1 and a[0][0] == x or (len(set(a[1][:])) == 1 and a[0][1] == x) or (len(set(a[2][:])) == 1 and a[0][0] == x):
		return 1
	return 0
inf = 10 ** 9 + 7

def main():
	karmanya = int(input())
	while karmanya != 0:
		karmanya -= 1
		(n, k) = map(int, input().split())
		a = list(map(int, input().split()))
		d = defaultdict(list)
		paint = [i for i in range(1, k + 1)]
		for i in range(n):
			d[a[i]].append(i)
		ans = [0] * n
		excess = []
		for i in d:
			if len(d[i]) >= k:
				for j in range(k):
					ans[d[i][j]] = j + 1
			else:
				excess += d[i]
		limit = len(excess) // k * k
		for i in range(limit):
			ans[excess[i]] = i % k + 1
		print(*ans)
main()


import typing
from collections import Counter

def solve(n: int, k: int, a: typing.List[int]) -> typing.NoReturn:
	a = [x - 1 for x in a]
	cnt = Counter(a)
	cc = Counter(cnt.values())
	r = sum((c * cc[c] for c in range(1, k))) // k + sum((cc[c] for c in range(k, n + 1)))
	r *= k
	a = sorted(enumerate(a), key=lambda x: (-cnt[x[1]], x[1]))
	c = 0
	p = [0] * n
	color = [0] * n
	for (i, x) in a:
		if not r:
			break
		if p[x] == k:
			continue
		color[i] = c + 1
		p[x] += 1
		c += 1
		c %= k
		r -= 1
	print(*color)

def main():
	t = int(input())
	for _ in range(t):
		(n, k) = map(int, input().split())
		(*a,) = map(int, input().split())
		solve(n, k, a)
main()


from collections import Counter, defaultdict

def f(a, k):
	ind = defaultdict(list)
	for i in range(len(a)):
		ind[a[i]].append(i)
	color = [0] * len(a)
	temp = 1
	for i in ind:
		for j in range(min(len(ind[i]), k)):
			color[ind[i][j]] = temp
			temp += 1
			if temp > k:
				temp = 1
	cnt = Counter(color)
	mn = float('inf')
	for i in range(1, k + 1):
		mn = min(mn, cnt[i])
	for i in range(len(color)):
		if cnt[color[i]] > mn:
			cnt[color[i]] -= 1
			color[i] = 0
	return color
for i in range(int(input())):
	(n, k) = map(int, input().strip().split())
	l = list(map(int, input().strip().split()))
	print(*f(l, k))


import sys
I = lambda x=' ': map(int, sys.stdin.readline().split(x))
pr = lambda *x, sep=' ', end='\n': sys.stdout.write(f'{sep.join(map(str, x))}{end}')

def solve():
	(n, k) = I()
	a = [*I()]
	d = dict()
	for (i, x) in enumerate(a):
		if x in d:
			if len(d[x]) < k:
				d[x].append(i)
		else:
			d[x] = [i]
	m = sum(map(lambda x: len(x[1]), d.items()))
	m -= m % k
	(ans, c) = ([0] * n, 0)
	for e in d:
		for i in d[e]:
			ans[i] = c + 1
			c = (c + 1) % k
			m -= 1
			if not m:
				return ans

def main():
	(t,) = I()
	for _ in range(t):
		pr(*solve())
main()


from itertools import product
from math import ceil, gcd, sqrt
import string
from decimal import Decimal

def binary_table(string_with_all_characters, length_to_make):
	return [''.join(x) for x in product(string_with_all_characters, repeat=length_to_make)]

def all_possible_substrings(string):
	return [int(string[i:j]) for i in range(len(string)) for j in range(i + 1, len(string) + 1)]

def number_of_substrings(length):
	return int(length * (length + 1) / 2)
for enumeration in range(int(input())):
	temp = {}
	(num_of_elements, num_of_colors) = map(int, input().split())
	array = list(map(int, input().split()))
	current_color = 1
	indexes = {}
	for i in range(len(array)):
		value = array[i]
		if temp.get(value) is None:
			temp[value] = 1
		else:
			temp[value] += 1
		if indexes.get(value) is None:
			indexes[value] = [i]
		else:
			indexes[value].append(i)
		if temp[value] > num_of_colors:
			array[i] = 0
			indexes[value].remove(i)
			temp[value] -= 1
	length_value = len([x for x in array if x > 0])
	num = 0
	while length_value % num_of_colors:
		if array[num] != 0:
			indexes[array[num]].remove(num)
			array[num] = 0
			length_value -= 1
		num += 1
	build = array[:]
	for i in temp:
		possible_index = indexes[i]
		for j in possible_index:
			build[j] = current_color
			current_color += 1
			if current_color > num_of_colors:
				current_color = 1
	print(*build)


MULTIPLE_CASE = True

def solve():
	(n, k) = [int(i) for i in input().split(' ')]
	data = [[] for _ in range(n)]
	a = [int(i) - 1 for i in input().split(' ')]
	colors = [0] * n
	for pos in range(n):
		data[a[pos]].append(pos)
	not_enough = 0
	for pos in data:
		if len(pos) >= k:
			for j in range(k):
				colors[pos[j]] = j + 1
		elif 0 < len(pos) < k:
			not_enough += len(pos)
	not_enough -= not_enough % k
	for pos in data:
		if 0 < len(pos) < k:
			for i in pos:
				if not_enough > 0:
					colors[i] = not_enough % k + 1
					not_enough -= 1
				else:
					break
	for i in colors:
		print('{} '.format(i), end='')
	print()
T = 1
if MULTIPLE_CASE:
	T = int(input())
while T > 0:
	T -= 1
	solve()


def cf_734B(numbers: list, k: int):
	counts = {}
	answer = [0] * len(numbers)
	for (index, num) in enumerate(numbers):
		if num in counts:
			counts[num][0] += 1
			counts[num][1].append(index)
		else:
			counts[num] = [1, [index]]
	extras = []
	for (count, indices) in counts.values():
		if count >= k:
			for i in range(k):
				answer[indices[i]] = i + 1
		else:
			for i in indices:
				extras.append(i)
	while len(extras) >= k:
		for i in range(k):
			answer[extras.pop()] = i + 1
	return answer
for _ in range(int(input())):
	(_, k) = map(int, input().split())
	print(*cf_734B(list(map(int, input().split())), k))


from collections import defaultdict
t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	f = defaultdict(int)
	a = list(map(int, input().split()))
	for nn in a:
		f[nn] += 1
		if f[nn] > k:
			f[nn] = k
	pl = {}
	curr = 0
	legal_sum = sum(f.values()) - sum(f.values()) % k
	sum_ = 0
	halfway = 0
	bads = []
	for (j, v) in f.items():
		sum_ += v
		pl[j] = curr
		if sum_ > legal_sum:
			if curr + v > k:
				halfway = j
			bads.append(j)
		curr = (curr + v) % k
	kk = {kk_: 0 for kk_ in f.keys()}
	c = [0] * n
	for j in range(n):
		if a[j] not in bads:
			if kk[a[j]] < k:
				c[j] = (pl[a[j]] + kk[a[j]]) % k + 1
				kk[a[j]] += 1
		elif halfway == a[j]:
			if pl[a[j]] + kk[a[j]] < k:
				c[j] = (pl[a[j]] + kk[a[j]]) % k + 1
				kk[a[j]] += 1
	s = ''
	for c_ in c:
		s += '{} '.format(c_)
	print(s[:-1])


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

def func():
	index_dic = defaultdict(list)
	for (ind, val) in enumerate(s):
		index_dic[val].append(ind)
	ans = [0 for x in range(n)]
	rem = set()
	for val in index_dic:
		if len(index_dic[val]) >= k:
			for ind in range(k):
				ans[index_dic[val][ind]] = ind + 1
		else:
			rem.add(val)
	total = 0
	for i in rem:
		total += len(index_dic[i])
	to_color = total - total % k
	color = 1
	done = 0
	flag = True if to_color else False
	for val in index_dic:
		if val in rem:
			if not flag:
				break
			for ind in range(len(index_dic[val])):
				if flag:
					ans[index_dic[val][ind]] = color
					color += 1
					done += 1
				if done >= to_color:
					flag = False
				if color > k:
					color = 1
	print(*ans)
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = list(map(int, input().split()))
	func()


from collections import defaultdict
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split(' '))
	nums = list(map(int, input().split(' ')))
	d = defaultdict(list)
	for i in range(n):
		if len(d[nums[i]]) < k:
			d[nums[i]].append(i)
	count = 0
	for (key, v) in d.items():
		count += len(v)
	count = count - count % k
	color = 0
	ans = [0 for i in range(n)]
	for key in sorted(d.keys()):
		for x in d[key]:
			color += 1
			ans[x] = color
			color %= k
			count -= 1
			if count == 0:
				break
		if count == 0:
			break
	print(' '.join((str(x) for x in ans)))


import sys
from collections import defaultdict
_DEBUG = False
if _DEBUG:
	fd = open('input.txt', 'r')
	sys.stdin = fd

def process(color, s):
	for l in indices.values():
		for i in l:
			color += 1
			res[i] = color
			color %= k
			s -= 1
			if s == 0:
				return
for t in range(int(sys.stdin.readline())):
	(n, k) = map(int, sys.stdin.readline().split())
	arr = list(map(int, sys.stdin.readline().split()))
	indices = defaultdict(list)
	for i in range(n):
		if len(indices[arr[i]]) < k:
			indices[arr[i]].append(i)
	s = 0
	for l in indices.values():
		s += len(l)
	s -= s % k
	res = [0] * n
	color = 0
	process(color, s)
	print(*res)


def solve():
	(n, k) = map(int, input().split())
	cnt = [0] * (n + 1)
	a = []
	for (i, x) in enumerate(map(int, input().split())):
		if cnt[x] < k:
			a.append((x, i))
		cnt[x] += 1
	a.sort()
	cc = 0
	color = [0] * n
	m = len(a) - len(a) % k
	for (x, i) in a[:m]:
		color[i] = cc + 1
		cc = (cc + 1) % k
	print(*color)
t = int(input())
for _ in range(t):
	solve()


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

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

def insr():
	s = input()
	return s

def invr():
	return map(int, input().split())
n = inp()
for _ in range(n):
	[c, k] = inlt()
	s = inlt()
	dict = {}
	for i in range(len(s)):
		if s[i] not in dict:
			dict[s[i]] = 1
		else:
			dict[s[i]] += 1
	res = [0] * c
	cnt = 0
	tmp = {}
	for x in dict:
		if dict[x] > k:
			tmp[x] = [cnt, cnt, cnt + k]
			cnt += k
		else:
			tmp[x] = [cnt, cnt, cnt + dict[x]]
			cnt += dict[x]
	cnt = cnt // k * k
	for i in range(c):
		if tmp[s[i]][1] < tmp[s[i]][2] and tmp[s[i]][1] < cnt:
			res[i] = tmp[s[i]][1] % k + 1
			tmp[s[i]][1] += 1
		else:
			res[i] = 0
	print(' '.join(map(str, res)))


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

def dbg(*args, **kwargs):
	_print('\x1b[95m', end='')
	_print(*args, **kwargs)
	_print('\x1b[0m', end='')

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

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

def mpint():
	return map(int, inp().split(' '))

def itg():
	return int(inp())
from collections import Counter, defaultdict

def to_table(iterable):
	d = defaultdict(lambda : [])
	for (i, e) in enumerate(iterable):
		d[e].append(i)
	return d

def solve():
	(n, k) = mpint()
	arr = tuple(mpint())
	counter = Counter(arr)
	big = frozenset(filter(lambda key: counter[key] >= k, counter))
	small = frozenset(counter) - big
	small_num = sum(map(counter.__getitem__, small))
	small_num -= small_num % k
	ans = [0] * n
	table = to_table(arr)
	for b in big:
		for (color, idx) in enumerate(table[b][:k], 1):
			ans[idx] = color
	color = 0
	for s in small:
		for idx in table[s]:
			if not small_num:
				break
			small_num -= 1
			color = (color + 1) % k
			ans[idx] = color + 1
		else:
			continue
		break
	check = Counter(ans)
	del check[0]
	assert len(frozenset(check.values())) == 1
	return ans

def main():
	for _ in range(itg()):
		print(*solve())
DEBUG = 0
URL = 'https://codeforces.com/contest/1551/problem/B2'
if DEBUG == 1:
	import requests
	from ACgenerator.Y_Test_Case_Runner import TestCaseRunner
	runner = TestCaseRunner(main, URL)
	inp = runner.input_stream
	print = runner.output_stream
	runner.checking()
else:
	if DEBUG != 2:
		dbg = lambda *args, **kwargs: ...
		(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	if DEBUG == 3:

		def print(*args, **kwargs):
			_print(*args, **kwargs)
			sys.stdout.flush()
	main()


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	cnt = [[] for i in range(n)]
	num = 0
	a = list(map(int, input().split()))
	for i in range(len(a)):
		if len(cnt[a[i] - 1]) < k:
			cnt[a[i] - 1].append(i)
			num += 1
	group = num // k
	group_end = k * group
	colors = [0 for i in range(n)]
	d = 0
	n = 0
	for i in cnt:
		if n == group_end:
			break
		for j in i:
			colors[j] = d + 1
			d = (d + 1) % k
			n += 1
			if n == group_end:
				break
	print(*colors)


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	final_ans = [0] * n
	d = {}
	for i in range(n):
		if d.get(a[i]) is None:
			d[a[i]] = [1, i]
		else:
			d[a[i]][0] += 1
			d[a[i]].append(i)
	h = []
	for (key, v) in d.items():
		if v[0] >= k:
			for i in range(1, k + 1):
				final_ans[v[i]] = i
		else:
			for i in range(1, v[0] + 1):
				h.append(v[i])
	count = 0
	l = len(h) // k * k
	for i in range(l):
		final_ans[h[i]] = count % k + 1
		count = count + 1
	print(*final_ans)


import os
import sys
from collections import Counter
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 main():
	t = int(input())
	for _ in range(t):
		(n, k) = map(int, input().split())
		l = list(map(int, input().split()))
		ans = [0 for i in range(n)]
		d = Counter(l)
		idxs = Counter()
		single = 0
		for i in d:
			if d[i] < k:
				single += d[i]
			idxs[i] = []
		for i in range(n):
			idxs[l[i]].append(i)
		for i in d:
			if d[i] >= k:
				for j in range(k):
					ans[idxs[i][j]] = j + 1
		if single >= k:
			c = 1
			v = 0
			flag = 0
			req = single // k * k
			for i in d:
				if d[i] < k:
					for j in range(len(idxs[i])):
						ans[idxs[i][j]] = v + 1
						v = (v + 1) % k
						c += 1
						if c == req + 1:
							flag = 1
							break
				if flag == 1:
					break
		print(*ans)
main()


from collections import defaultdict
t = int(input())
while t > 0:
	t -= 1
	line = input().split()
	(n, k) = (int(line[0]), int(line[1]))
	d = defaultdict(list)
	line = input().split()
	for i in range(n):
		x = line[i]
		if len(d[x]) < k:
			d[x].append(i)
	res = ['0'] * n
	color = 0
	cnt = sum([len(x) for x in d.values()])
	cnt -= cnt % k
	for (_, v) in d.items():
		for i in v:
			color += 1
			res[i] = str(color)
			color = color % k
			cnt -= 1
			if cnt == 0:
				break
		if cnt == 0:
			break
	print(' '.join(res))


import collections as cc
import bisect as bi
import heapq as hp
import math as mt
import itertools as it
import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
for tc in range(int(input())):
	(n, k) = I()
	ar = I()
	last = []
	temp = cc.defaultdict(list)
	ans = [0] * n
	for i in range(n):
		temp[ar[i]].append(i)

	def chh(i, j):
		if ar[i][j] == 1:
			return 0
		for (dx, dy) in dr:
			newi = i + dx
			newj = j + dy
			if 0 <= newi < n and 0 <= newj < m and (ar[newi][newj] == 1):
				return 0
		return 1
	for now in temp:
		then = temp[now]
		if len(then) >= k:
			for i in range(k):
				ans[then[i]] = i + 1
		else:
			last += then
	cur = len(last) // k
	i = 0

	def ch(i):
		ans = i * 4 // 3
		if ans % 4 == 0:
			ans -= 1
		return ans
	while i < cur * k:
		for j in range(k):
			ans[last[i]] = j + 1
			i += 1
	print(*ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	d = [[] for z in range(n + 1)]
	ans = [0 for z in range(n)]
	for z in range(n):
		d[a[z]].append(z)
	c = 0
	temp = []
	for z in range(1, n + 1):
		num = 1
		for y in d[z]:
			temp.append(y)
			num += 1
			c += 1
			ans[y] = c
			c = c % k
			l = len(temp)
			if k == l:
				temp.clear()
			if num > k:
				break
	l = len(temp)
	for z in range(l):
		ans[temp[z]] = 0
	print(*ans)


import sys

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

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

def get_list_string():
	return list(map(str, sys.stdin.readline().strip().split()))

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

def get_int():
	return int(sys.stdin.readline().strip())

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

def get_print(x):
	sys.stdout.write(x + '\n')

def get_print_int_same(x):
	sys.stdout.write(str(x) + ' ')

def get_print_same(x):
	sys.stdout.write(x + ' ')
from sys import maxsize

def solve():
	for _ in range(get_int()):
		(n, k) = get_ints()
		arr = get_list()
		d = dict()
		maxx = 0
		for i in range(n):
			if arr[i] not in d:
				d[arr[i]] = [i]
				maxx += 1
			elif len(d[arr[i]]) <= k - 1:
				d[arr[i]].append(i)
				maxx += 1
		ans = [0] * n
		start = 1
		mul = maxx // k
		upper = mul * k
		for (key, v) in d.items():
			if upper == 0:
				break
			for ind in v:
				if upper == 0:
					break
				ans[ind] = start
				start += 1
				upper -= 1
				if start > k:
					start = 1
		get_print(' '.join(map(str, ans)))
solve()


from collections import Counter, defaultdict
import sys
input = sys.stdin.readline
T = int(input())
for _ in range(T):
	(n, k) = map(int, input().split())
	data = list(map(int, input().split()))
	counter = Counter(data)
	idx = defaultdict(list)
	answer = [-1] * n
	for i in range(n):
		idx[data[i]].append(i)
	li = list(counter.items())
	li = sorted(li, reverse=True, key=lambda x: (x[1], x[0]))
	temp_idx = 0
	remain = 0
	for key in counter.keys():
		if counter[key] >= k:
			pass
		else:
			remain += counter[key]
	for (val, cnt) in li:
		if cnt >= k:
			for (cnt2, id) in enumerate(idx[val]):
				if cnt2 < k:
					answer[id] = cnt2 + 1
				else:
					answer[id] = 0
		else:
			for (cnt2, id) in enumerate(idx[val]):
				if temp_idx >= remain - remain % k:
					answer[id] = 0
				else:
					answer[id] = temp_idx % k + 1
				temp_idx += 1
	print(' '.join(map(str, answer)))


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	l = list(map(int, input().split()))
	d = {}
	for i in range(n):
		x = l[i]
		if d.get(x, -1) == -1:
			d[x] = [i]
		elif len(d[x]) != k:
			d[x].append(i)
	c = 0
	for i in d:
		c += len(d[i])
	c = c // k * k
	res = [0] * n
	j = 1
	for index in d:
		for i in d[index]:
			res[i] = j
			j += 1
			c -= 1
			if c == 0:
				break
			if j == k + 1:
				j = 1
		if c == 0:
			break
	print(*res)


t = int(input())
for i in range(t):
	(n, k) = list(map(int, input().strip().split()))
	a = list(map(int, input().strip().split()))
	freqarray = [0 for i in range(n + 1)]
	ans = [0 for i in range(n)]
	for x in a:
		freqarray[x] += 1
	c = n
	for x in freqarray:
		if x > k:
			c = c - (x - k)
	c = (c - c % k) // k
	r = [[] for i in range(int(n + 1))]
	for i in range(n):
		r[a[i]].append(i)
	for x in r:
		colour = 1
		l = len(x)
		if l >= k:
			for i in range(l):
				ans[x[i]] = colour
				if colour < k and colour > 0:
					colour += 1
				elif colour == k:
					colour = 0
	colour = 1
	for x in r:
		l = len(x)
		if l > 0 and l < k:
			for i in range(l):
				ans[x[i]] = colour
				if colour < k:
					colour += 1
				elif colour == k:
					colour = 1
	colours = [0 for i in range(k)]
	for x in ans:
		if x > 0 and colours[x - 1] < c:
			print(x, end=' ')
			colours[x - 1] += 1
		else:
			print(0, end=' ')
	print()


import sys

def process(n, k, a):
	counts = {}
	indices = {}
	for i in range(len(a)):
		if a[i] in counts:
			counts[a[i]] += 1
		else:
			counts[a[i]] = 1
		if a[i] in indices:
			indices[a[i]].append(i)
		else:
			indices[a[i]] = [i]
	counter = 0
	to_sort = []
	for i in counts:
		counter += min(counts[i], k)
		to_sort.append((i, min(counts[i], k)))
	to_sort.sort(key=lambda x: x[1], reverse=True)
	to_return = [0] * n
	paint_number = 0
	paint_max = int(counter / k) * k
	for (i, j) in to_sort:
		painted = 0
		while painted < j:
			if paint_number == paint_max:
				return to_return
			to_return[indices[i][painted]] = paint_number % k + 1
			paint_number += 1
			painted += 1
	return to_return
t = int(input())
for i in range(t):
	(n, k) = [int(x) for x in input().split()]
	a = [int(x) for x in input().split()]
	sys.stdout.write(' '.join(map(str, process(n, k, a))) + '\n')


NUM = int(input())
for T in range(0, NUM):
	(n, k) = map(int, input().split())
	vallist = list(map(int, input().split()))
	answer = [0] * n
	countnum = [[] for i in range(0, n)]
	for i in range(0, n):
		countnum[vallist[i] - 1].append(i)
	ans = 0
	for i in range(0, n):
		ans += min(k, len(countnum[i]))
	ans //= k
	current = 0
	for i in countnum:
		for j in range(0, min(k, len(i))):
			if ans:
				answer[i[j]] = current + 1
				current = (current + 1) % k
				ans -= current == 0
	for i in answer:
		print(i, end=' ')
	print('')


i = int(input(''))
li = [0] * i
for a in range(i):
	count = {}
	l2 = input('')
	l2 = l2.split(' ')
	length = int(l2[0])
	color = int(l2[1])
	stri = input('')
	lis = stri.split(' ')
	for i in range(len(lis)):
		lis[i] = int(lis[i])
	for j in range(len(lis)):
		if lis[j] in count:
			count[lis[j]].append(j)
		else:
			count[lis[j]] = [j]
	finallis = [0] * length
	sum = 0
	for key in count:
		if len(count[key]) >= color:
			sum += len(count[key])
			ini = 1
			for i in count[key]:
				if ini <= color:
					finallis[i] = ini
					ini += 1
				else:
					finallis[i] = 0
	num = (length - sum) // color
	unpainted = (length - sum) % color
	ini = 1
	round = 0
	unpain = 0
	for key in count:
		if len(count[key]) < color:
			for i in count[key]:
				if round < num:
					if ini < color:
						finallis[i] = ini
						ini += 1
					else:
						finallis[i] = color
						ini = 1
						round = round + 1
				elif unpain < unpainted:
					finallis[i] = 0
					unpain += 1
	li[a] = finallis
for i in range(len(li)):
	for j in li[i]:
		print(j, end=' ')
	if i < len(li) - 1:
		print('')


from collections import defaultdict
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	A = list(map(int, input().split()))
	B = defaultdict(lambda : [])
	for (i, a) in enumerate(A):
		if len(B[a]) < k:
			B[a].append(i)
	B = sorted(zip(B.keys(), B.values()), key=lambda k: -len(k[1]))
	BB = []
	for b in B:
		BB += b[1]
	res = n * [0]
	for i in range(len(BB) // k * k):
		res[BB[i]] = i % k + 1
	print(*res)


import sys
pl = 1
sys.setrecursionlimit(10 ** 5)
if pl:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('outpt.txt', 'w')

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

def fi():
	return int(input())

def si():
	return list(input().rstrip())

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

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

def google(tc, *ans):
	print('Case #' + str(tc) + ':', *ans)
t = fi()
f = t

def check(a):
	c = 0
	for i in range(n):
		if a[i] != b[i]:
			c += 1
	return c
while t > 0:
	t -= 1
	(n, k) = mi()
	a = li()
	d = {}
	f = []
	for i in range(n):
		if a[i] not in d:
			d[a[i]] = []
		d[a[i]].append(i)
	ans = [0] * n
	for i in d:
		if len(d[i]) >= k:
			for j in range(k):
				ans[d[i][j]] = j + 1
		else:
			f += d[i]
	p = len(f) // k * k
	j = 1
	for i in range(p):
		ans[f[i]] = j
		j += 1
		if j > k:
			j = 1
	print(*ans)


from collections import Counter
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	a = [int(i) for i in input().split()]
	freq = Counter(a)
	lessThanK = 0
	for i in freq:
		if freq[i] >= k:
			freq[i] = k
		else:
			lessThanK += freq[i]
	lessThanK -= lessThanK % k
	color = 1
	lessThanKFreqColor = {}
	for i in freq:
		if freq[i] < k:
			lessThanKFreqColor[i] = [min(freq[i], lessThanK), color]
			color += lessThanKFreqColor[i][0]
			lessThanK -= lessThanKFreqColor[i][0]
		if color > k:
			color -= k
	res = []
	for i in a:
		if i in lessThanKFreqColor:
			if lessThanKFreqColor[i][0] > 0:
				res.append(lessThanKFreqColor[i][1])
				lessThanKFreqColor[i][0] -= 1
				lessThanKFreqColor[i][1] += 1
				if lessThanKFreqColor[i][1] > k:
					lessThanKFreqColor[i][1] -= k
			else:
				res.append(0)
		elif freq[i] > 0:
			res.append(freq[i])
			freq[i] -= 1
		else:
			res.append(0)
	print(' '.join((str(i) for i in res)))


import os
import sys
import math
from io import BytesIO, IOBase
import io
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
from collections import Counter
import threading
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')

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree1:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)
MOD = 10 ** 9 + 7

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod = 10 ** 9 + 7
omod = 998244353
prime = [True for i in range(10001)]
prime[0] = prime[1] = False

def SieveOfEratosthenes(n=10000):
	p = 2
	c = 0
	while p <= n:
		if prime[p] == True:
			c += 1
			for i in range(p, n + 1, p):
				prime[i] = False
		p += 1

class DSU:

	def __init__(self, R, C):
		self.par = range(R * C + 1)
		self.rnk = [0] * (R * C + 1)
		self.sz = [1] * (R * C + 1)

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

	def union(self, x, y):
		(xr, yr) = (self.find(x), self.find(y))
		if xr == yr:
			return
		if self.rnk[xr] < self.rnk[yr]:
			(xr, yr) = (yr, xr)
		if self.rnk[xr] == self.rnk[yr]:
			self.rnk[xr] += 1
		self.par[yr] = xr
		self.sz[xr] += self.sz[yr]

	def size(self, x):
		return self.sz[self.find(x)]

	def top(self):
		return self.size(len(self.sz) - 1) - 1

class LazySegTree:

	def __init__(self, _op, _e, _mapping, _composition, _id, v):

		def set(p, x):
			assert 0 <= p < _n
			p += _size
			for i in range(_log, 0, -1):
				_push(p >> i)
			_d[p] = x
			for i in range(1, _log + 1):
				_update(p >> i)

		def get(p):
			assert 0 <= p < _n
			p += _size
			for i in range(_log, 0, -1):
				_push(p >> i)
			return _d[p]

		def prod(l, r):
			assert 0 <= l <= r <= _n
			if l == r:
				return _e
			l += _size
			r += _size
			for i in range(_log, 0, -1):
				if l >> i << i != l:
					_push(l >> i)
				if r >> i << i != r:
					_push(r >> i)
			sml = _e
			smr = _e
			while l < r:
				if l & 1:
					sml = _op(sml, _d[l])
					l += 1
				if r & 1:
					r -= 1
					smr = _op(_d[r], smr)
				l >>= 1
				r >>= 1
			return _op(sml, smr)

		def apply(l, r, f):
			assert 0 <= l <= r <= _n
			if l == r:
				return
			l += _size
			r += _size
			for i in range(_log, 0, -1):
				if l >> i << i != l:
					_push(l >> i)
				if r >> i << i != r:
					_push(r - 1 >> i)
			l2 = l
			r2 = r
			while l < r:
				if l & 1:
					_all_apply(l, f)
					l += 1
				if r & 1:
					r -= 1
					_all_apply(r, f)
				l >>= 1
				r >>= 1
			l = l2
			r = r2
			for i in range(1, _log + 1):
				if l >> i << i != l:
					_update(l >> i)
				if r >> i << i != r:
					_update(r - 1 >> i)

		def _update(k):
			_d[k] = _op(_d[2 * k], _d[2 * k + 1])

		def _all_apply(k, f):
			_d[k] = _mapping(f, _d[k])
			if k < _size:
				_lz[k] = _composition(f, _lz[k])

		def _push(k):
			_all_apply(2 * k, _lz[k])
			_all_apply(2 * k + 1, _lz[k])
			_lz[k] = _id
		_n = len(v)
		_log = _n.bit_length()
		_size = 1 << _log
		_d = [_e] * (2 * _size)
		_lz = [_id] * _size
		for i in range(_n):
			_d[_size + i] = v[i]
		for i in range(_size - 1, 0, -1):
			_update(i)
		self.set = set
		self.get = get
		self.prod = prod
		self.apply = apply
MIL = 1 << 20

def makeNode(total, count):
	return total * MIL + count

def getTotal(node):
	return math.floor(node / MIL)

def getCount(node):
	return node - getTotal(node) * MIL
nodeIdentity = makeNode(0.0, 0.0)

def nodeOp(node1, node2):
	return node1 + node2
	return makeNode(getTotal(node1) + getTotal(node2), getCount(node1) + getCount(node2))
identityMapping = -1

def mapping(tag, node):
	if tag == identityMapping:
		return node
	count = getCount(node)
	return makeNode(tag * count, count)

def composition(mapping1, mapping2):
	return mapping1 if mapping1 != identityMapping else mapping2

def memodict(f):

	class memodict(dict):

		def __missing__(self, key):
			ret = self[key] = f(key)
			return ret
	return memodict().__getitem__

def pollard_rho(n):
	if n & 1 == 0:
		return 2
	if n % 3 == 0:
		return 3
	s = (n - 1 & 1 - n).bit_length() - 1
	d = n >> s
	for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
		p = pow(a, d, n)
		if p == 1 or p == n - 1 or a % n == 0:
			continue
		for _ in range(s):
			prev = p
			p = p * p % n
			if p == 1:
				return math.gcd(prev - 1, n)
			if p == n - 1:
				break
		else:
			for i in range(2, n):
				(x, y) = (i, (i * i + 1) % n)
				f = math.gcd(abs(x - y), n)
				while f == 1:
					(x, y) = ((x * x + 1) % n, (y * y + 1) % n)
					y = (y * y + 1) % n
					f = math.gcd(abs(x - y), n)
				if f != n:
					return f
	return n

@memodict
def prime_factors(n):
	if n <= 1:
		return Counter()
	f = pollard_rho(n)
	return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f)

def distinct_factors(n):
	factors = [1]
	for (p, exp) in prime_factors(n).items():
		factors += [p ** i * factor for factor in factors for i in range(1, exp + 1)]
	return factors

def all_factors(n):
	(small, large) = ([], [])
	for i in range(1, int(n ** 0.5) + 1, 2 if n & 1 else 1):
		if not n % i:
			small.append(i)
			large.append(n // i)
	if small[-1] == large[-1]:
		large.pop()
	large.reverse()
	small.extend(large)
	return small

def binarySearch(arr, n, i, key):
	left = 0
	right = n - 1
	mid = 0
	res = n
	while left <= right:
		mid = (right + left) // 2
		if arr[mid][i] > key:
			res = mid
			right = mid - 1
		else:
			left = mid + 1
	return res

def binarySearch1(arr, n, i, key):
	left = 0
	right = n - 1
	mid = 0
	res = -1
	while left <= right:
		mid = (right + left) // 2
		if arr[mid][i] > key:
			right = mid - 1
		else:
			res = mid
			left = mid + 1
	return res
t = 1
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	d = defaultdict(list)
	for i in range(n):
		d[a[i]].append(i)
	ans = [0] * n
	excess = []
	for i in d:
		if len(d[i]) >= k:
			for j in range(k):
				ans[d[i][j]] = j + 1
		else:
			excess += d[i]
	limit = len(excess) - len(excess) % k
	for i in range(limit):
		ans[excess[i]] = i % k + 1
	print(*ans)


import sys
input = sys.stdin.readline
from collections import defaultdict as dd
I = lambda : list(map(int, input().split()))
(t,) = I()
for _ in range(t):
	(n, k) = I()
	l = I()
	dct = dd(list)
	an = [0] * n
	rem = []
	for i in range(n):
		dct[l[i]].append(i)
	for lt in dct.values():
		if len(lt) >= k:
			for i in range(k):
				an[lt[i]] = i + 1
		else:
			rem += lt
	pos = len(rem) // k
	i = 0
	while i < pos * k:
		for j in range(k):
			an[rem[i]] = j + 1
			i += 1
	print(*an)


from collections import Counter, deque, defaultdict
from heapq import *

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

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

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

def task():
	(n, k) = mapInput()
	a = arrInput()
	c = defaultdict(int)
	pos = defaultdict(list)
	for (i, x) in enumerate(a):
		pos[x].append(i)
		c[x] += 1
	res = [0] * n
	posLeft = []
	unique = 0
	for key in c:
		if c[key] >= k:
			for i in range(k):
				res[pos[key][i]] = i + 1
		else:
			unique += c[key]
			posLeft.extend(pos[key])
	leftSetsPos = unique // k * k
	for i in range(leftSetsPos):
		res[posLeft[i]] = i % k + 1
	print(*res)
for _ in range(inp()):
	task()


for i in range(int(input())):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	(a, z) = ({}, 0)
	for i in range(n):
		if x[i] in a:
			if len(a[x[i]]) < k:
				a[x[i]].append(i)
		else:
			a[x[i]] = [i]
	b = []
	for c in a.values():
		for i in c:
			b.append(i)
	(ans, kol) = ([0] * n, len(b) // k * k)
	for i in range(kol):
		ans[b[i]] = i % k + 1
	print(*ans)


import bisect
import math
import collections
import sys
import copy
from functools import reduce
import decimal
sys.setrecursionlimit(10 ** 9)
decimal.getcontext().rounding = decimal.ROUND_HALF_UP
graphDict = collections.defaultdict
queue = collections.deque

class Graphs:

	def __init__(self):
		self.graph = graphDict(list)

	def add_edge(self, u, v):
		self.graph[u].append(v)

	def dfs_utility(self, nodes, visited_nodes):
		visited_nodes.add(nodes)
		for neighbour in self.graph[nodes]:
			if neighbour not in visited_nodes:
				self.dfs_utility(neighbour, visited_nodes)
			else:
				return neighbour

	def dfs(self, node):
		Visited = set()
		self.dfs_utility(node, Visited)

	def bfs(self, node):
		visited = set()
		if node not in visited:
			queue.append(node)
			visited.add(node)
		while queue:
			parent = queue.popleft()
			print(parent)
			for item in self.graph[parent]:
				if item not in visited:
					queue.append(item)
					visited.add(item)

def rounding(n):
	return int(decimal.Decimal(f'{n}').to_integral_value())

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))

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

def map_inp(v_type):
	return map(v_type, inp().split())

def list_inp(v_type):
	return list(map_inp(v_type))
for _ in range(int(inp())):
	(n, k) = map_inp(int)
	s = list_inp(int)
	dic = collections.Counter(s)
	count = 0
	ans = 0
	index__ = {}
	for i in range(len(s)):
		if s[i] not in index__:
			index__[s[i]] = []
			index__[s[i]].append(i)
		else:
			index__[s[i]].append(i)
	index = []
	for item in dic.keys():
		if dic[item] >= k:
			count += k
			temp = 0
			for i in index__[item]:
				if s[i] == item and temp < k:
					index.append(i)
					temp += 1
		else:
			count += dic[item]
			for i in index__[item]:
				if s[i] == item:
					index.append(i)
	count -= count % k
	i = 1
	ans = [0 for item in range(n)]
	for item in index[:count]:
		if i <= k:
			ans[item] = i
			i += 1
		else:
			i = 1
			ans[item] = i
			i += 1
	print(*ans)


from collections import Counter
from itertools import cycle
for i in range(int(input())):
	(n, k) = (int(i) for i in input().split())
	a = [int(i) for i in input().split()]
	c = Counter(a)
	s = 0
	for i in c:
		c[i] = min(c[i], k)
		s += c[i]
	lim = s // k
	cyc = iter(cycle([i for i in range(k)]))
	d = [set() for i in range(k)]
	cnt1 = 0
	cnt2 = 0
	for x in c:
		cnt2 = 0
		for i in cyc:
			d[i].add(x)
			cnt1 += 1
			cnt2 += 1
			if cnt1 == k * lim or cnt2 == c[x]:
				break
		if cnt1 == k * lim:
			break
	ds = 0
	ans = []
	for x in a:
		for i in range(ds, len(d)):
			if x in d[i]:
				d[i].remove(x)
				ans.append(i + 1)
				break
		else:
			ans.append(0)
		while ds < len(d) and len(d[ds]) == 0:
			ds += 1
	print(*ans)


import sys
N = int(200000.0 + 5)
sys.setrecursionlimit(N)

def charming():
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(zip(a, range(n)))
	b.sort(key=lambda x: x[0])
	cnt = 0
	color = [0] * n
	c = 1
	stk = list()
	for i in range(n):
		if i == 0 or b[i - 1][0] != b[i][0]:
			cnt = 1
		else:
			cnt += 1
		if cnt > k:
			continue
		else:
			color[b[i][1]] = (c - 1) % k + 1
			c += 1
			stk.append(i)
	c = (c - 1) % k + 1
	siz = len(stk)
	for i in range(siz - (c - 1), siz):
		color[b[stk[i]][1]] = 0
	for i in color:
		print(i, end=' ')
	print()
for t in range(int(input())):
	charming()


import sys
input = lambda : sys.stdin.readline().rstrip()
T = int(input())
for t in range(T):
	(N, K) = map(int, input().split())
	arr = sorted([(v, i) for (i, v) in enumerate(map(int, input().split()))])
	lasts = [-1] * len(arr)
	res = [0] * len(arr)
	d = dict()
	for (v, i) in arr:
		if v not in d:
			d[v] = 0
		else:
			d[v] += 1
	arr_overK = []
	arr_underK = []
	for (v, i) in arr:
		if d[v] >= K:
			arr_overK.append((v, i))
		else:
			arr_underK.append((v, i))
	last = -1
	k = 0
	for (v, i) in arr_overK:
		if v != last:
			k = 0
		if k >= K:
			pass
		else:
			res[i] = k + 1
			k += 1
		last = v
	k = 0
	for i in range(len(arr_underK) - len(arr_underK) % K):
		(v, i) = arr_underK[i]
		res[i] = k + 1
		k += 1
		k %= K
	print(*res)


from collections import Counter, defaultdict

def solve(line, k):
	counter = Counter(line)
	(all_colors, white) = (dict(), dict())
	left = {}
	total_left = 0
	for (el, value) in counter.items():
		if value >= k:
			all_colors[el] = 1
			white[el] = value - k
		else:
			left[el] = value
			total_left += value
	custom_colors = defaultdict(list)
	color_ptr_unique = 1
	boundary = total_left - total_left % k
	current = 0
	for (el, value) in left.items():
		if current + value > boundary:
			left[el] = boundary - current
			white[el] = value - (boundary - current)
			current = boundary
		for ii in range(left[el]):
			custom_colors[el].append(color_ptr_unique)
			color_ptr_unique += 1
			if color_ptr_unique > k:
				color_ptr_unique = 1
		current += value
	answer = []
	color_ptr_repeat = defaultdict(lambda : 1)
	for char in line:
		if char in white and white[char] > 0:
			answer.append(0)
			white[char] -= 1
		elif char in all_colors:
			answer.append(color_ptr_repeat[char])
			color_ptr_repeat[char] += 1
		else:
			color = custom_colors[char].pop()
			answer.append(color)
	return answer

def main():
	t = int(input())
	for _ in range(t):
		(n, k) = list(map(int, input().split()))
		line = list(map(int, input().split()))
		answ = solve(line, k)
		print(*answ)
main()


tt = int(input())
for _ in range(tt):
	(n, k) = map(int, input().split())
	m = {}
	seq = list(map(int, input().split()))
	for c in seq:
		if c in m:
			m[c] += 1
		else:
			m[c] = 1
	p = 0
	base = {}
	shift = {}
	for c in m:
		if m[c] >= k:
			base[c] = 0
			shift[c] = 0
		else:
			shift[c] = 0
			base[c] = p
			p += m[c]
	p_limit = p - p % k
	for c in seq:
		if shift[c] < k and (m[c] >= k or shift[c] + base[c] < p_limit):
			print((shift[c] + base[c]) % k + 1, end=' ')
			shift[c] += 1
		else:
			print(0, end=' ')
	print()


from collections import Counter, defaultdict, deque
test = int(input())
for t in range(test):
	(n, k) = map(int, input().split())
	arr = list(map(int, input().split()))
	c = defaultdict(list)
	ans = [0] * n
	for (j, v) in enumerate(arr):
		c[v].append(j)
	tmp = []
	for j in c:
		if len(c[j]) >= k:
			for i in range(k):
				ans[c[j][i]] = i + 1
		else:
			for i in range(len(c[j])):
				tmp.append(c[j][i])
	while len(tmp) >= k:
		for j in range(k):
			ans[tmp.pop()] = j + 1
	ans = list(map(str, ans))
	print(' '.join(ans))


from collections import defaultdict
T = int(input())
for _ in range(T):
	(n, k) = [int(i) for i in input().split()]
	nums = [int(i) for i in input().split()]
	x = defaultdict(set)
	for (i, xx) in enumerate(nums):
		if len(x[xx]) < k:
			x[xx].add(i)
	ans = [0] * n
	for (i, v) in x.items():
		if len(v) == k:
			for (ii, j) in enumerate(v):
				ans[j] = ii + 1
	items = []
	l = 0
	for (_, xxx) in x.items():
		for nnn in xxx:
			ans[nnn] = l + 1
			l += 1
			items.append(nnn)
			if l % k == 0:
				l = 0
				items = []
	for i in items:
		ans[i] = 0
	print(' '.join((str(i) for i in ans)))


from collections import defaultdict
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	tab = list(map(int, input().split()))
	freq = dict()
	res = [0] * n
	positions = defaultdict(list)
	nb_element_can_be_colored = 0
	for (i, val) in enumerate(tab):
		if len(positions[val]) < k:
			positions[val].append(i)
			nb_element_can_be_colored += 1
	max_element_to_color = nb_element_can_be_colored - nb_element_can_be_colored % k
	current_color = 0
	solve = False
	for pos in positions.values():
		if solve:
			break
		for index in pos:
			res[index] = current_color + 1
			current_color = (current_color + 1) % k
			max_element_to_color -= 1
			if max_element_to_color == 0:
				solve = True
				break
	print(' '.join(list(map(str, res))))


def solve(n, k, a):
	indices = [[] for i in range(n + 1)]
	colours = [0] * n
	cur_col = 0
	max_painted = 0
	for i in range(n):
		if len(indices[a[i]]) < k:
			indices[a[i]] += [i]
			max_painted += 1
	max_painted = max_painted - max_painted % k
	for arr in indices:
		for x in arr:
			colours[x] = cur_col % k + 1
			cur_col += 1
			if cur_col >= max_painted:
				print(*colours)
				return
	print(*colours)
for t in range(int(input())):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	solve(n, k, a)


import os, sys
from io import BytesIO, IOBase
from collections import deque, Counter, defaultdict as dft
from heapq import heappop, heappush
from math import log, sqrt, factorial, cos, tan, sin, radians, log2, ceil, floor
from bisect import bisect, bisect_left, bisect_right
from decimal import *
import sys, threading
from itertools import permutations, combinations
from copy import deepcopy
input = sys.stdin.readline
ii = lambda : int(input())
si = lambda : input().rstrip()
mp = lambda : map(int, input().split())
ms = lambda : map(str, input().strip().split(' '))
ml = lambda : list(mp())
mf = lambda : map(float, input().split())
alphs = 'abcdefghijklmnopqrstuvwxyz'

def solve():
	(n, k) = mp()
	s = ml()
	dct = dft(list)
	for i in range(n):
		dct[s[i]].append(i)
	fre = [0] * k
	res = [0] * n
	pre = 0
	for (c, f) in dct.items():
		if len(f) >= k:
			i = 0
			for idx in f[:k]:
				fre[i] += 1
				res[idx] = i + 1
				i += 1
		else:
			for i in range(len(f)):
				fre[pre] += 1
				res[f[i]] = pre + 1
				pre = (pre + 1) % k
	mn = min(fre)
	hata = dft(int)
	for i in range(n):
		num = res[i]
		t = hata[num]
		if t == mn:
			res[i] = 0
		else:
			hata[num] += 1
	print(*res)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

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


def colors(N, K, arr):
	arr.sort()
	count = 1
	curr = 1
	req = [arr[0]]
	for i in range(1, N):
		if arr[i][0] == arr[i - 1][0]:
			curr += 1
			if curr <= K:
				count += 1
				req.append(arr[i])
		else:
			curr = 1
			count += 1
			req.append(arr[i])
	del arr
	color_count = [0] * (K + 1)
	color = [0] * N
	for i in range(len(req)):
		if (i + 1) % K == 0 and color_count[K] + 1 <= count // K:
			color[req[i][1]] = K
			color_count[K] += 1
		elif color_count[(i + 1) % K] + 1 <= count // K:
			color[req[i][1]] = (i + 1) % K
			color_count[(i + 1) % K] += 1
	return color
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	arr = [[int(x), i] for (i, x) in enumerate(input().split())]
	print(*colors(n, k, arr))


import sys
input = lambda : sys.stdin.readline()
int_arr = lambda : list(map(int, input().split()))
str_arr = lambda : list(map(str, input().split()))
get_str = lambda : map(str, input().split())
get_int = lambda : map(int, input().split())
get_flo = lambda : map(float, input().split())
mod = 1000000007

def solve(n, k, a):
	ans = [0] * n
	d = {}
	for i in range(n):
		if a[i] not in d:
			d[a[i]] = []
		d[a[i]].append(i)
	tmp = []
	for c in d.keys():
		for i in range(min(len(d[c]), k)):
			tmp.append(d[c][i])
			if len(tmp) == k:
				for j in range(k):
					ans[tmp[j]] = j + 1
				tmp = []
	print(*ans)
for _ in range(int(input())):
	(n, k) = get_int()
	arr = int_arr()
	solve(n, k, arr)


from sys import stdin
input = lambda : stdin.readline().strip()
lin = lambda : list(map(int, input().split()))
iin = lambda : int(input())
main = lambda : map(int, input().split())
from math import ceil, sqrt, factorial, log
from collections import deque
from bisect import bisect_left
mod = 998244353
mod = 1000000007

def solve(we):
	(n, k) = main()
	l = lin()
	for i in range(n):
		l[i] = [l[i], i]
	ans = [0] * n
	j = 0
	l.sort()
	prev = -1
	t = 1
	for i in range(n):
		if l[i][0] == prev:
			if t >= k:
				pass
			else:
				ans[l[i][1]] = j + 1
				j += 1
				j = j % k
				t += 1
		else:
			prev = l[i][0]
			t = 1
			ans[l[i][1]] = j + 1
			j = j + 1
			j = j % k
	d = {}
	for i in range(n):
		if ans[i] != 0:
			if ans[i] not in d:
				d[ans[i]] = []
			d[ans[i]].append(i)
	mi = float('infinity')
	for i in d:
		mi = min(mi, len(d[i]))
	for i in d:
		if len(d[i]) > mi:
			for j in range(len(d[i]) - mi):
				ans[d[i][j]] = 0
	print(*ans)
qwe = 1
qwe = iin()
for _ in range(qwe):
	solve(_ + 1)


from collections import Counter
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	arr = list(map(int, input().split()))
	d = Counter(arr)
	occ = {}
	d1 = []
	for i in range(n):
		if arr[i] not in occ:
			occ[arr[i]] = []
		occ[arr[i]].append(i)
	ans = [-1] * n
	for k1 in d.keys():
		if d[k1] >= k:
			i = 0
			while i < k:
				idx = occ[k1][i]
				ans[idx] = i + 1
				i += 1
			while i < d[k1]:
				idx = occ[k1][i]
				ans[idx] = 0
				i += 1
		else:
			d1.extend(occ[k1])
	i = 0
	c = 1
	m = len(d1)
	if i + k <= m:
		while i < m:
			ans[d1[i]] = c
			c += 1
			i += 1
			if c > k:
				c = 1
				if i + k > m:
					break
	while i < m:
		ans[d1[i]] = 0
		i += 1
	for v in ans:
		print(v, end=' ')
	print()


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

def so():
	return int(input())

def st():
	return input()

def mj():
	return map(int, input().strip().split(' '))

def msj():
	return map(str, input().strip().split(' '))

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

def lebe():
	return list(map(int, input()))

def dmain():
	sys.setrecursionlimit(1000000)
	threading.stack_size(1024000)
	thread = threading.Thread(target=main)
	thread.start()

def joro(L):
	return ''.join(map(str, L))

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

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

def read():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def tr(n):
	return n * (n + 1) // 2

def main():
	for i in range(so()):
		(n, q) = mj()
		L = le()
		B = []
		d = 0
		for i in range(n):
			B.append(0)
		Z = [[] for i in range(1 + n)]
		M = []
		P = []
		Y = []
		for i in range(1 + n):
			M.append(0)
		for i in range(1 + n):
			P.append(0)
		for u in range(n):
			if q > P[L[u]]:
				P[L[u]] += 1
				Z[L[u]].append(u)
		for r in range(1 + n):
			for v in Z[r]:
				Y.append(v)
		er = len(Y) // q * q
		for p in range(0, er, q):
			bec = 0
			for ut in range(p, q + p, 1):
				B[Y[ut]] = 1 + bec
				bec = 1 + bec
		for i in B:
			print(i, end=' ')
		print('\n')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

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


from sys import stdin, stdout
final_ans = ''
for tests in range(int(stdin.readline())):
	(n, k) = map(int, stdin.readline().split())
	ls = list(map(int, stdin.readline().split()))
	ind_ls = [[] for i in range(n + 1)]
	cnt_ls = [0] * (n + 1)
	for i in range(n):
		ind_ls[ls[i]].append(i)
		cnt_ls[ls[i]] += 1
	arr = []
	for i in range(n + 1):
		if cnt_ls[i] > 0:
			arr.append([cnt_ls[i], i])
	arr.sort()
	ans = [0] * n
	cnt = 1
	n1 = len(arr)
	left_num = n
	for i in range(n1 - 1, -1, -1):
		if arr[i][0] >= k:
			for j in range(k):
				ans[ind_ls[arr[i][1]][j]] = j + 1
			left_num -= arr[i][0]
		else:
			for j in range(arr[i][0]):
				if left_num >= k - cnt + 1:
					ans[ind_ls[arr[i][1]][j]] = cnt
					cnt += 1
					left_num -= 1
					if cnt == k + 1:
						cnt -= k
				else:
					break
	for i in ans:
		final_ans += str(i) + ' '
	final_ans += '\n'
stdout.write(final_ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	d = {}
	all = [0] * n
	temp = []
	for i in range(n):
		if a[i] in d:
			d[a[i]] += 1
		else:
			d[a[i]] = 1
		if d[a[i]] <= k:
			temp.append((a[i], i))
	for i in range(len(temp) % k):
		temp.pop()
	temp.sort()
	idx = 1
	for i in temp:
		all[i[1]] = idx
		idx += 1
		if idx == k + 1:
			idx = 1
	for i in all:
		print(i, end=' ')
	print('')


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	ar = list(map(int, input().split()))
	dic = {}
	li = []
	count = 0
	for i in range(n):
		if ar[i] in dic:
			if dic[ar[i]] < k:
				dic[ar[i]] += 1
				li.append(i)
				count += 1
		else:
			dic[ar[i]] = 1
			count += 1
			li.append(i)
	el = count // k
	ext = len(li) - el * k
	li = li[ext:]
	li.sort(key=lambda x: ar[x])
	ans = [0] * n
	for i in range(len(li)):
		ans[li[i]] = i % k + 1
	print(*ans)


def kth(ref_lis, c_list):
	c = 1
	for i in c_list:
		ref_lis[i] = c
		c += 1
for test in range(int(input())):
	(n, k) = map(int, input().split())
	st = list(input().split())
	dic = {}
	for i in range(n):
		if dic.get(st[i], -1) == -1:
			dic[st[i]] = [i]
		elif len(dic[st[i]]) < k:
			dic[st[i]].append(i)
	ans = [0] * n
	nls = []
	for itm in dic.values():
		if len(itm) == k:
			kth(ans, itm)
		else:
			nls.extend(itm)
	p = len(nls) // k * k
	c = 1
	for i in range(p):
		if i % k == 0:
			ans[nls[i]] = k
		else:
			ans[nls[i]] = i % k
	print(*ans)


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	arr = list(map(int, input().split()))
	idx = [[] for i in range(n + 1)]
	col = [0 for i in range(n)]
	for i in range(n):
		idx[arr[i]].append(i)
	less_k_idx = []
	for id in idx:
		if len(id) >= k:
			for i in range(k):
				col[id[i]] = i + 1
		elif len(id) > 0:
			less_k_idx += id
	z = len(less_k_idx) // k * k
	for i in range(z):
		col[less_k_idx[i]] = i % k + 1
	print(*col)


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	sc = dict()
	for i in range(n):
		if a[i] in sc.keys():
			sc[a[i]][0] += 1
			sc[a[i]][1].append(i)
		else:
			sc[a[i]] = [1, [i]]
	ans = [0] * n
	it_min = 0
	cnt_min = 0
	for key in sc.keys():
		if sc[key][0] < k:
			cnt_min += sc[key][0]
	cnt_min -= cnt_min % k
	for key in sc.keys():
		if sc[key][0] >= k:
			it = 1
			for i in range(k):
				ans[sc[key][1][i]] = it
				it += 1
		elif it_min < cnt_min:
			for i in sc[key][1]:
				ans[i] = it_min % k + 1
				it_min += 1
				if it_min == cnt_min:
					break
	print(*ans)


t = int(input())
for u in range(t):
	(n, k) = map(int, input().split())
	b = [int(p) for p in input().split()]
	a = [0] * n
	m = {}
	x = 0
	for i in range(n):
		if m.get(b[i]):
			if len(m[b[i]]) < k:
				m[b[i]].append(i)
				x += 1
		else:
			m[b[i]] = [i]
			x += 1
	x -= x % k
	c = 0
	for i in m:
		for j in m[i]:
			c += 1
			a[j] = c
			c %= k
			x -= 1
			if x == 0:
				break
		if x == 0:
			break
	print(*a)


t = int(input())
while t:
	t -= 1
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	(di, li, pq) = ({}, [], [0] * (n + 1))
	for i in range(n):
		if di.get(a[i]):
			di[a[i]].append(i + 1)
		else:
			di[a[i]] = [i + 1]
	for i in list(di.values()):
		if len(i) <= k:
			li.extend(i)
		else:
			r = 1
			for j in range(len(i)):
				pq[i[j]] = r
				r += 1
				if r > k:
					break
	(gi, o) = (len(li) // k, 0)
	if o < len(li) and gi > 0:
		while o < len(li) and gi > 0:
			(q, val, y) = (o, k, 1)
			if val > 0:
				while q < len(li) and val > 0:
					pq[li[q]] = y
					y += 1
					val -= 1
					q += 1
			o = q
			gi -= 1
	print(*pq[1:])


import collections
t = int(input())
for _ in range(t):
	(N, K) = [int(s) for s in input().split(' ')]
	seq = [int(s) for s in input().split(' ')]
	indices = collections.defaultdict(list)
	res = [0 for _ in seq]
	current_color = 1
	used = [0 for _ in range(K + 1)]
	bigger_than_k = set()
	for (i, c) in enumerate(seq):
		indices[c].append([i, -1])
	for (c, idx) in indices.items():
		if len(idx) > K:
			bigger_than_k.add(c)
	for (c, idx) in indices.items():
		if c not in bigger_than_k:
			for i in range(len(idx)):
				idx[i][1] = current_color
				used[current_color] += 1
				if current_color == K:
					current_color = 1
				else:
					current_color += 1
	minimum_val = min(used[1:])
	used = [minimum_val for _ in range(K + 1)]
	for (c, idx) in indices.items():
		if c in bigger_than_k:
			values = idx[:K]
			color = 1
			for (i, _) in values:
				res[i] = color
				color += 1
		else:
			values = idx
			for (i, color) in values:
				if used[color] > 0:
					res[i] = color
					used[color] -= 1
	print(' '.join([str(s) for s in res]))


def wonderfulColoring(n, colors, array):
	d = {}
	ans = {}
	for x in array:
		if x in d:
			d[x] += 1
		else:
			d[x] = 1
		ans[x] = []
	for x in d:
		if d[x] > colors:
			d[x] = colors
	s = 0
	for x in d:
		s += d[x]
	r = s % colors
	for x in d:
		if d[x] > r:
			d[x] -= r
			r = 0
			break
		else:
			r -= d[x]
			d[x] = 0
			if r == 0:
				break
	c = 1
	for x in d:
		i = 0
		while i < d[x]:
			i += 1
			ans[x].append(c)
			c += 1
			c = c % k
			if c == 0:
				c = colors
	res = []
	for x in range(n):
		if not ans[array[x]]:
			res.append(0)
		else:
			p = ans[array[x]].pop()
			res.append(p)
	return res
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	l = list(map(int, input().split()))
	ans = wonderfulColoring(n, k, l)
	for x in ans:
		print(x, end=' ')
	print()


for t in range(int(input())):
	(n, k) = map(int, input().split())
	A = [int(i) for i in input().split()]
	c_count = n // k * k
	(B, d, d1) = (A[:], dict(), dict())
	for i in B:
		d[i] = d[i] + 1 if i in d else 1
	for i in range(n):
		if B[i] in d1:
			d1[B[i]].append(i)
		else:
			d1[B[i]] = [i]
	B.sort(key=lambda x: (d[x], x), reverse=True)
	(X, i, j, lst) = ([B[0]], 0, n, B[0])
	while j > 0:
		if B[i] != lst:
			X.append(B[i])
			lst = B[i]
		i += 1
		j -= 1
	C = []
	a = [int(i) for i in range(k, 0, -1)]
	for i in range(len(X)):
		if d[X[i]] > k:
			C += a
			rem = d[X[i]] - k
			while rem > 0:
				C.append(0)
				rem -= 1
		else:
			cal = n - len(C)
			a1 = cal // k
			for i in range(a1):
				C += a
			rem2 = n - len(C)
			while rem2 > 0:
				C.append(0)
				rem2 -= 1
			break
	(b, k) = (0, 0)
	for i in X:
		Y = d1[i]
		for j in Y:
			B[j] = C[k]
			k += 1
	print(*B)


from sys import *
from math import floor
input = lambda : stdin.readline()
int_arr = lambda : list(map(int, stdin.readline().strip().split()))
str_arr = lambda : list(map(str, stdin.readline().split()))
get_str = lambda : map(str, stdin.readline().strip().split())
get_int = lambda : map(int, stdin.readline().strip().split())
get_float = lambda : map(float, stdin.readline().strip().split())
mod = 1000000007
setrecursionlimit(1000)
for _ in range(int(input())):
	(n, k) = get_int()
	arr = int_arr()
	ans = [0] * n
	dic = {}
	for i in range(n):
		if arr[i] in dic:
			dic[arr[i]] += [i]
		else:
			dic[arr[i]] = [i]
	rem = []
	for val in dic.values():
		if len(val) >= k:
			for i in range(k):
				ans[val[i]] = i + 1
		else:
			rem += val
	extra = len(rem) // k * k
	ind = 0
	while ind < extra:
		for i in range(k):
			ans[rem[ind]] = i + 1
			ind += 1
	print(*ans)


from collections import Counter
import string
import math
import bisect
import sys
from fractions import Fraction

def array_int():
	return [int(i) for i in sys.stdin.readline().split()]

def vary(arrber_of_variables):
	if arrber_of_variables == 1:
		return int(sys.stdin.readline())
	if arrber_of_variables >= 2:
		return map(int, sys.stdin.readline().split())

def makedict(var):
	return dict(Counter(var))
testcases = vary(1)
for _ in range(testcases):
	(n, k) = vary(2)
	s = array_int()
	pt = []
	for i in range(n):
		pt.append([s[i], i])
	pt.sort()
	ans = [-1] * n
	i = 0
	dicti = makedict(sorted(s))
	rem = 0
	while i < n:
		z = dicti[pt[i][0]]
		if z >= k:
			for j in range(k):
				ans[pt[i][1]] = j + 1
				i += 1
			for j in range(k, z):
				ans[pt[i][1]] = 0
				i += 1
		else:
			rem += z
			i += z
	i = 0
	j = 1
	pte = ans.count(-1) // k
	while pte > 0 and i < n:
		if ans[pt[i][1]] == -1:
			ans[pt[i][1]] = j
			j += 1
			i += 1
		else:
			i += 1
		if j == k + 1:
			pte -= 1
			j = 1
	for i in range(len(ans)):
		if ans[i] == -1:
			ans[i] = 0
	print(*ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	l = list(map(int, input().split()))
	d = {}
	for i in range(n):
		if l[i] in d:
			d[l[i]] += 1
		else:
			d[l[i]] = 1
		if d[l[i]] > k:
			d[l[i]] = k
	dc = {i: 0 for i in range(k)}
	ans = {}
	p = 0
	for i in d:
		ans[i] = []
		for j in range(d[i]):
			ans[i].append(p)
			dc[p] += 1
			p += 1
			if p == k:
				p = 0
	m = min(list(dc.values()))
	res = [-1 for i in range(n)]
	for i in range(n):
		if l[i] in ans and len(ans[l[i]]) > 0:
			temp = ans[l[i]].pop()
			if dc[temp] > m:
				dc[temp] -= 1
			else:
				res[i] = temp
	res = [i + 1 for i in res]
	print(*res)


R = lambda : map(int, input().split())
p = print
t = 1
(t,) = R()
alpali = list(map(chr, range(97, 123)))

def solve():
	(n, k) = R()
	li = list(enumerate(list(R())))
	li.sort(key=lambda x: x[1])
	di = {}
	lia = [0] * len(li)
	cnt = 1
	for i in range(len(li)):
		if di.get(li[i][1], 0) < k:
			lia[li[i][0]] = cnt
			di[li[i][1]] = di.get(li[i][1], 0) + 1
			cnt += 1
			if cnt == k + 1:
				cnt = 1
		if i == len(li) - 1:
			j = i
			while j >= 0 and lia[li[j][0]] != k:
				lia[li[j][0]] = 0
				j -= 1
	for a in lia:
		p(a, end=' ')
	p()
while t:
	t -= 1
	solve()


from collections import Counter

def solve():
	(n, k) = map(int, input().split())
	arr = list(map(int, input().split()))
	temp = []
	ans = [0 for i in range(n)]
	d = dict()
	for i in range(n):
		if arr[i] in d:
			d[arr[i]] += 1
		else:
			d[arr[i]] = 1
		temp.append([arr[i], i])
	temp = sorted(temp)
	i = 0
	cur = 1
	last = [0 for i in range(k + 1)]
	while i < n:
		t = temp[i][0]
		if d[temp[i][0]] >= k:
			x = 1
			l = i + d[temp[i][0]]
			while i < n and i < l:
				if x <= k:
					ans[temp[i][1]] = x
					x += 1
				i += 1
		else:
			l = i + d[temp[i][0]]
			while i < n and i < l:
				ans[temp[i][1]] = cur
				last[cur] = temp[i][1]
				cur += 1
				if cur > k:
					cur = 1
				i += 1
	if cur > 1:
		for i in range(cur - 1, 0, -1):
			ans[last[i]] = 0
	print(*ans)
t = int(input())
for _ in range(t):
	solve()


T = int(input())
t = 0
while t < T:
	(N, K) = map(int, input().split())
	L = list(map(int, input().split()))
	C = [0 for n in range(N)]
	P = [0 for n in range(N + 1)]
	S = []
	for n in range(N):
		P[L[n]] += 1
		if P[L[n]] <= K:
			S.append([L[n], n])
	bianchi = 0
	for n in range(N):
		if P[n] > K:
			bianchi = bianchi + P[n] - K
	M = N - bianchi
	M = len(S)
	M = M // K * K
	H = S[:M]
	S.sort()
	a0 = S[0][0]
	p = S[0][1]
	C[p] = 1
	k = min(2, K)
	col = 1
	tot = 1
	for n in range(1, M):
		a = S[n][0]
		p = S[n][1]
		if a == a0:
			if tot < K:
				C[p] = k
				col += 1
				tot = tot + 1
				k = k + 1
				if k == K + 1:
					k = 1
		else:
			tot = 1
			C[p] = k
			col += 1
			k = k + 1
			if k == K + 1:
				k = 1
		a0 = a
	t += 1
	print(*C)


from sys import stdin, stdout
input = stdin.readline
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	a = [int(x) for x in input().split()]
	d = {}
	c = -1
	for i in a:
		c += 1
		if i not in d:
			d[i] = []
		if len(d[i]) < k:
			d[i].append(c)
	ans = [0 for i in range(n)]
	vals = sorted(d.keys(), key=lambda x: len(d[x]), reverse=True)
	kk = 0
	make_zero = []
	for i in vals:
		for j in d[i]:
			kk += 1
			if kk == k + 1:
				make_zero = []
				kk = 1
			ans[j] = kk
			make_zero.append(j)
	assert kk == len(make_zero)
	if kk != k:
		for i in make_zero:
			ans[i] = 0
	print(*ans)


from collections import defaultdict
t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	l = list(map(int, input().split()))
	m = defaultdict(int)
	m2 = defaultdict(int)
	for i in range(n):
		if m[l[i]] < k:
			m[l[i]] += 1
		m2[l[i]] += 1
	c = [0] * n
	dp = []
	for i in range(n):
		if m2[l[i]] >= k and m[l[i]] > 0:
			c[i] = m[l[i]]
			m[l[i]] -= 1
		elif m2[l[i]] < k and m[l[i]] > 0:
			dp.append((l[i], i))
		else:
			c[i] = m[l[i]]
	dp.sort()
	temp = k
	for i in range(len(dp)):
		if i < len(dp) - len(dp) % k:
			c[dp[i][1]] = temp
			temp -= 1
			if temp == 0:
				temp = k
		else:
			c[dp[i][1]] = 0
	print(*c, sep=' ')


import os
import sys
from io import BytesIO, IOBase
import math
from queue import Queue
import collections
import itertools
import bisect
import heapq
import random

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):
	cnt = []
	while n % 2 == 0:
		cnt.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			cnt.append(i)
			n = n / i
	if n > 2:
		cnt.append(int(n))
	return cnt

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

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
	i = 2
	while i * i <= n:
		if primes[i] == True:
			for j in range(i * i, n + 1, i):
				primes[j] = False
		i += 1
	pr = []
	for i in range(0, n + 1):
		if primes[i]:
			pr.append(i)
	return pr

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 sod(n):
	s = 0
	while n > 0:
		s += n % 10
		n //= 10
	return s
for xyz in range(0, int(input())):
	(n, k) = map(int, input().split())
	l = list(map(int, input().split()))
	MA = max(l)
	pos = [[] for i in range(0, MA + 1)]
	tc = 0
	for i in range(0, n):
		if len(pos[l[i]]) < k:
			pos[l[i]].append(i)
			tc += 1
	col = [[] for i in range(0, k)]
	trim = tc % k
	cc = 0
	for i in range(0, len(pos)):
		cl = pos[i]
		for j in range(0, len(cl)):
			if trim > 0:
				trim -= 1
				continue
			col[cc].append(pos[i][j])
			cc = (cc + 1) % k
	ans = [0] * n
	for i in range(0, len(col)):
		cuco = i + 1
		cl = col[i]
		for j in cl:
			ans[j] = cuco
	print(*ans)


import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')
from itertools import chain
t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	el_idx = {}
	for (i, ai) in enumerate(a):
		el_ai = el_idx.setdefault(ai, [])
		if len(el_ai) < k:
			el_ai.append(i)
	cnt = {el: len(el_idx[el]) for el in el_idx.keys()}
	pos_el = sum(cnt.values())
	pos_col = pos_el // k
	res = ['0' for _ in range(n)]
	col_iter = chain(*[range(1, k + 1) for _ in range(pos_col)])
	idx_iter = chain(*el_idx.values())
	for (idx, col) in zip(idx_iter, col_iter):
		res[idx] = str(col)
	print(' '.join(res))


import sys
import math
import bisect
import heapq
from bisect import bisect_right
from sys import stdin, stdout

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

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

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

def get_list_of_list(n):
	return [list(map(int, sys.stdin.readline().strip().split())) for _ in range(n)]

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

def myceil(x, y):
	return (x + y - 1) // y

def Solution(arr, n, k):
	hm = {}
	for i in range(n):
		if arr[i] in hm:
			hm[arr[i]].append(i)
		else:
			hm[arr[i]] = [i]
	res = [0 for _ in range(n)]
	tmp = []
	for el in hm:
		if len(hm[el]) >= k:
			mn = k
			while mn:
				res[hm[el].pop()] = mn
				mn -= 1
		else:
			for v in hm[el]:
				tmp.append(v)
	for i in range(0, len(tmp) - k + 1, k):
		for j in range(k):
			res[tmp[i + j]] = j + 1
	print(*res)

def main():
	for _ in range(get_int()):
		(n, k) = get_ints_in_variables()
		arr = get_ints_in_list()
		Solution(arr, n, k)
main()


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	s = list(map(int, input().split()))
	a = [0 for i in range(n + 1)]
	b = [0 for i in range(n + 1)]
	e = [[] for i in range(n + 1)]
	c = 0
	for i in range(n):
		a[s[i]] += 1
	for i in range(1, n + 1):
		if a[i] >= k:
			b[i] = k
		else:
			b[i] += a[i]
			c += a[i]
	d = c % k
	for i in range(1, n + 1):
		if d == 0:
			break
		if b[i] != k:
			if b[i] > d:
				b[i] -= d
				break
			else:
				d -= b[i]
				b[i] = 0
	x = 1
	for i in range(1, n + 1):
		for j in range(b[i]):
			e[i].append(x)
			if x == k:
				x = 1
			else:
				x += 1
	for i in range(n):
		if b[s[i]] == 0:
			print(0, end=' ')
		else:
			print(e[s[i]][b[s[i]] - 1], end=' ')
			b[s[i]] -= 1
	print()