This problem is actually a subproblem of problem G from the same contest.

There are $n$ candies in a candy box. The type of the $i$-th candy is $a_i$ ($1 \le a_i \le n$).

You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all distinct (i. e. for example, a gift having two candies of type $1$ and two candies of type $2$ is bad). 

It is possible that multiple types of candies are completely absent from the gift. It is also possible that not all candies of some types will be taken to a gift.

Your task is to find out the maximum possible size of the single gift you can prepare using the candies you have.

You have to answer $q$ independent queries.

If you are Python programmer, consider using PyPy instead of Python when you submit your code.


-----Input-----

The first line of the input contains one integer $q$ ($1 \le q \le 2 \cdot 10^5$) — the number of queries. Each query is represented by two lines.

The first line of each query contains one integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of candies.

The second line of each query contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le n$), where $a_i$ is the type of the $i$-th candy in the box.

It is guaranteed that the sum of $n$ over all queries does not exceed $2 \cdot 10^5$.


-----Output-----

For each query print one integer — the maximum possible size of the single gift you can compose using candies you got in this query with the restriction described in the problem statement.


-----Example-----
Input
3
8
1 4 8 4 5 6 3 8
16
2 1 3 3 4 3 4 4 1 3 2 2 2 4 1 1
9
2 2 4 4 4 7 7 7 7

Output
3
10
9



-----Note-----

In the first query, you can prepare a gift with two candies of type $8$ and one candy of type $5$, totalling to $3$ candies.

Note that this is not the only possible solution — taking two candies of type $4$ and one candy of type $6$ is also valid.

Difficulty: MEDIUM
Tags: Sorting

Greedy algorithms
Skill types: Sorting

Greedy algorithms

Starter code:

Solutions:
import sys
input = sys.stdin.readline
from collections import Counter
q = int(input())
for _ in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	cnt = list(Counter(a).items())
	cnt.sort(key=lambda k: k[1], reverse=True)
	prev = n + 1
	ans = 0
	for (_, c) in cnt:
		if prev > c:
			ans += c
			prev = c
		else:
			ans += prev - 1
			prev -= 1
		if prev == 0:
			break
	print(ans)


from sys import stdin, stdout
import bisect
import math

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

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

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

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

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

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

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

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

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

def solve():
	n = inp()
	x = []
	l = li()
	d = {}
	for i in l:
		d[i] = d.get(i, 0) + 1
	for i in d:
		x.append(d[i])
	x.sort(reverse=True)
	s = set()
	c = 0
	for i in x:
		if i not in s:
			c += i
			s.add(i)
		else:
			while i in s:
				i -= 1
			if i > 0:
				s.add(i)
				c += i
	print(c)
for _ in range(inp()):
	solve()


import sys
from collections import Counter

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

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

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

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

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
for _ in range(INT()):
	N = INT()
	A = LIST()
	C = Counter(A)
	MAX = max(C.values())
	C2 = Counter(C.values())
	for i in range(MAX, 1, -1):
		if C2[i] >= 2:
			C2[i - 1] += C2[i] - 1
			C2[i] = 1
	ans = sum(C2.keys())
	print(ans)


t = int(input())
sol = []
while t:
	t -= 1
	n = int(input())
	a = [int(i) for i in input().split()]
	d = {}
	for i in a:
		if not d.get(i):
			d[i] = 1
		else:
			d[i] += 1
	a = []
	for i in d.keys():
		a.append(d[i])
	a.sort(reverse=True)
	d = set()
	for i in a:
		if not i in d:
			d.add(i)
		else:
			j = i
			while j and j in d:
				j -= 1
			d.add(j)
	a = d
	sol.append(sum(a))
print(*sol, sep='\n')


from sys import stdin, stdout
I = stdin.readline
print = stdout.write
for _ in range(int(I())):
	n = int(I())
	a = list(map(int, I().split()))
	d = dict()
	for i in a:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	l = list(d.values())
	l.sort(reverse=True)
	ans = [l[0]]
	al = 1
	t = l[0]
	for i in range(1, len(l)):
		if t - l[i] > 0:
			ans.append(l[i])
			t = l[i]
		else:
			temp = l[i] - t
			temp += 1
			if l[i] - temp <= 0:
				break
			else:
				t = l[i] - temp
				ans.append(t)
	print(str(sum(ans)) + '\n')


from sys import stdin, stdout
input = stdin.readline
print = stdout.write
q = int(input())
for x in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	tab = [0] * (max(a) + 1)
	for item in a:
		tab[item] += 1
	tab.sort()
	i = len(tab) - 1
	o = tab[-1]
	s = 0
	while i >= 0 and o > 0:
		k = min(o, tab[i])
		o = k - 1
		s += k
		i -= 1
	print(str(s))
	print('\n')


from sys import stdin
for f in range(int(input())):
	junk = int(stdin.readline())
	data = [int(i) for i in input().split()]
	dic = [0] * (junk + 1)
	for d in data:
		dic[d] += 1
	dic.sort(reverse=True)
	ret = 0
	curr = dic[0] + 1
	for a in dic:
		if a < curr:
			curr = a
		else:
			curr -= 1
		ret += curr
		if curr == 1 or a == 0:
			break
	print(ret)


import sys
for _ in range(int(input())):
	n = [0] * int(input())
	for i in [int(i) for i in sys.stdin.readline().split()]:
		n[i - 1] += 1
	n.sort(reverse=True)
	S = 0
	curr = n[0] + 1
	for a in n:
		if a < curr:
			curr = a
		else:
			curr -= 1
		S += curr
		if curr == 1 or a == 0:
			break
	print(S)


from collections import Counter
import sys

def main():
	input = sys.stdin.readline
	q = int(input())
	for l in range(q):
		n = int(input())
		a = list(map(int, input().split()))
		b = sorted(Counter(a).values())[::-1]
		t = b[0]
		ans = b[0]
		for k in range(1, len(b)):
			if t == 0:
				break
			if b[k] >= t:
				ans += t - 1
				t -= 1
			else:
				ans += b[k]
				t = b[k]
		print(ans)
main()


m = int(input())
for ii in range(m):
	n = int(input())
	l = [int(i) for i in input().split()]
	s = [0 for _ in range(n)]
	for x in l:
		s[x - 1] += 1
	s = sorted(s)
	s.reverse()
	for i in range(1, n):
		if s[i] >= s[i - 1]:
			s[i] = max(s[i - 1] - 1, 0)
	print(sum(s))


import sys
input = sys.stdin.readline
q = int(input())
for _ in range(q):
	n = int(input())
	a = [int(i) for i in input().split()]
	c = {}
	for i in a:
		if i in c:
			c[i] += 1
		else:
			c[i] = 1
	bib = []
	for i in c:
		bib.append(c[i])
	bib = sorted(bib)[::-1]
	prev = bib[0] + 1
	su = 0
	for i in range(len(bib)):
		ne = min(prev - 1, bib[i])
		if ne <= 0:
			break
		su += ne
		prev = ne
	print(su)


q = int(input())
while q:
	n = int(input())
	data = list(map(int, input().split()))
	temp = set()
	cnt = {}
	for i in range(n):
		if data[i] in temp:
			cnt[data[i]] += 1
		else:
			cnt[data[i]] = 1
		temp.add(data[i])
	data2 = list()
	for el in temp:
		data2.append(cnt[el])
	data2.sort()
	data2.reverse()
	temp2 = set()
	ans = 0
	temp_count = 200000000
	for i in range(len(data2)):
		if data2[i] >= temp_count:
			ans += temp_count
			temp_count -= 1
			if temp_count <= 0:
				break
		else:
			ans += data2[i]
			temp_count = data2[i] - 1
			if temp_count <= 0:
				break
	print(ans)
	q -= 1


from collections import *
from sys import stdin

def input():
	return stdin.readline()
q = int(input())
for _ in range(q):
	n = int(input())
	aas = map(int, input().split())
	counts = [0] * (n + 1)
	for a in aas:
		counts[a] += 1
	counts.sort(reverse=True)
	total = 0
	mx = counts[0]
	for c in counts:
		inc = min(mx, c)
		if inc == 0:
			break
		mx = inc - 1
		total += inc
	print(total)


from collections import Counter
q = int(input())
for _ in range(q):
	n = int(input())
	a = [int(i) for i in input().split()]
	dic = {}
	for i in a:
		dic[i] = dic.get(i, 0) + 1
	c = sorted(list(dic.values()), reverse=True)
	res = 0
	pre = 1000000000.0
	for i in c:
		if pre > 0:
			if i < pre:
				res += i
				pre = i
			else:
				res += pre - 1
				pre = pre - 1
	print(res)


import sys
from collections import defaultdict
q = int(next(sys.stdin))
for _ in range(q):
	c = defaultdict(int)
	n = int(next(sys.stdin))
	a = map(int, next(sys.stdin).split(' '))
	for k in a:
		c[k] += 1
	candies = []
	for (t, amount) in c.items():
		candies.append((t, amount))
	candies = sorted(candies, key=lambda x: x[1])
	result = set()
	for (typ, amount) in candies:
		if amount not in result:
			result.add(amount)
		else:
			amount2 = amount
			while amount2 > 0:
				amount2 -= 1
				if amount2 not in result:
					result.add(amount2)
					break
	print(sum(result))


q = int(input())
for i in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	if n == 1:
		print(1)
		continue
	a.sort()
	j = 0
	b = list()
	count = 1
	while j < len(a) - 1:
		while j < len(a) - 1 and a[j] == a[j + 1]:
			j += 1
			count += 1
		b.append(count)
		j += 1
		count = 1
	if j == len(a) - 1:
		b.append(1)
	b.sort()
	b.reverse()
	del j
	cur = b[0]
	res = cur
	for j in range(1, len(b)):
		if b[j] == cur:
			res += b[j] - 1
			cur = b[j] - 1
		elif b[j] < cur:
			res += b[j]
			cur = b[j]
		else:
			res += cur - 1
			cur = cur - 1
		if cur <= 0:
			break
	print(res)


from sys import stdin
input = stdin.readline
q = int(input())
d = [0] * 200005
for query in range(q):
	n = int(input())
	for i in range(n + 1):
		d[i] = 0
	for i in input().split():
		d[int(i)] += 1
	ziom = d[:n + 1]
	ziom.sort()
	thres = 10000000
	wyn = 0
	bla = False
	for i in reversed(range(len(ziom))):
		if thres <= 0:
			print(wyn)
			bla = True
			break
		wyn += min(thres - 1, ziom[i])
		thres = min(thres - 1, ziom[i])
	if not bla:
		print(wyn)


import os

def _f(n, arr):
	t_n = [0] * (n + 1)
	for a in arr:
		t_n[a] += 1
	t_n.sort(reverse=True)
	k = None
	for i in range(1, n):
		if t_n[i] >= t_n[i - 1]:
			t_n[i] = t_n[i - 1] - 1
		if t_n[i] <= 0:
			t_n[i] = 0
			k = i
			break
	if k is None:
		return sum(t_n)
	else:
		s = 0
		i = 0
		while i < k:
			s += t_n[i]
			i += 1
		return s

def f(n, arr):
	return _f(n, arr)
if os.environ.get('DEBUG', False):
	print(f'{f(6, [1, 2, 2, 3, 3, 3])} = 6')
	print(f'{f(8, [1, 4, 8, 4, 5, 6, 3, 8])} = 3')
	print(f'{f(16, [2, 1, 3, 3, 4, 3, 4, 4, 1, 3, 2, 2, 2, 4, 1, 1])} = 10')
	print(f'{f(9, [2, 2, 4, 4, 4, 7, 7, 7, 7])} = 9')
else:
	q = int(input())
	for _ in range(q):
		n = int(input())
		arr = list(map(int, input().split()))
		print(f(n, arr))


from sys import stdin
input = stdin.readline

def sum(b, a):
	return a * (a + 1) // 2 - b * (b + 1) // 2
for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	d = {}
	for i in a:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	c = 0
	s = {}
	k = sorted(list(d.values()), reverse=True)
	now = k[0] + 1
	for i in range(len(k)):
		now = min(now - 1, k[i])
		if now > 0:
			c += now
	print(c)


for i in range(int(input())):
	n = int(input())
	sort_col = [0] * (n + 1)
	col_csort = [0] * (n + 1)
	t = 0
	for el in map(int, input().split()):
		col_csort[sort_col[el]] -= 1
		sort_col[el] += 1
		col_csort[sort_col[el]] += 1
		t = max(sort_col[el], t)
	cou = 0
	for j in range(t, 0, -1):
		if col_csort[j]:
			cou += j
			col_csort[j] -= 1
			if col_csort[j]:
				col_csort[j - 1] += col_csort[j]
	print(cou)


q = int(input())
for _ in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	count = [0] * (max(a) + 1)
	for i in a:
		count[i] += 1
	count.sort(reverse=True)
	req = count[0]
	ans = 0
	i = 0
	while req > 0:
		if i < len(count) and count[i] >= req:
			ans += req
			req -= 1
			i += 1
		else:
			req -= 1
	print(ans)


q = int(input())
for i in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	f = {}
	mx = 0
	mxi = 0
	for j in a:
		if j not in f:
			f[j] = 0
		f[j] += 1
	ans = 0
	d = sorted(f.items(), key=lambda kv: kv[1], reverse=True)
	mx = d[0][1]
	ans += mx
	k = 1
	for j in range(mx - 1, 0, -1):
		if k < len(d) and d[k][1] >= j:
			k += 1
			ans += j
			if k == len(d):
				break
	print(ans)


for _ in range(int(input())):
	n = int(input())
	li = list(map(int, input().split()))
	s = [0] * n
	for i in li:
		s[i - 1] += 1
	s.sort(reverse=True)
	m = 2 * 10 ** 6 + 1
	max_gs = 0
	for i in s:
		m = max(min(m - 1, i), 0)
		max_gs += m
	print(max_gs)


import sys
t = int(input())
for _ in range(t):
	n = int(sys.stdin.readline())
	a = list(map(int, sys.stdin.readline().split()))
	d = {}
	for i in a:
		d[i] = d.get(i, 0) + 1
	b = sorted(list(d.values()))
	ans = b[-1]
	ans1 = b[-1]
	for i in range(len(b) - 2, -1, -1):
		ans1 = min(ans1 - 1, b[i])
		if ans1 > 0:
			ans += ans1
		else:
			break
	print(ans)


import collections
T = int(input())
test = 0
while test < T:
	N = int(input())
	arr = input()
	arr = [int(num) for num in arr.split(' ')]
	if len(arr) == 1:
		print(1)
		test += 1
		continue
	res = 0
	counter = collections.Counter(arr)
	k = list(counter.values())
	k.sort(reverse=True)
	m = max(k)
	L = len(k)
	idx = 0
	while m > 0 and idx < L:
		m = min(m, k[idx])
		res += m
		m -= 1
		idx += 1
	print(res)
	test += 1


T = int(input())
for i in range(T):
	n = int(input())
	s = [list(map(int, input().split()))]
	p = {}
	q = {}
	for it in s:
		for j in range(n):
			if it[j] in q:
				q[it[j]] += 1
			else:
				q[it[j]] = 1
	for j in range(1, n + 1):
		if j in q:
			if q[j] in p:
				p[q[j]] += 1
			else:
				p[q[j]] = 1
	x = n
	ans = 0
	cnt = 0
	while x > 0:
		if x in p:
			cnt += p[x]
		if cnt > 0:
			ans += x
			cnt -= 1
		x -= 1
	print(ans)
	p.clear()
	q.clear()
	s.clear()


import sys
q = int(input())
lines = sys.stdin.readlines()
res = []
for i in range(q):
	n = int(lines[2 * i])
	bucket = {}
	for i in lines[2 * i + 1].split():
		if not bucket.get(i):
			bucket[i] = 0
		bucket[i] += 1
	values = sorted(list(bucket.values()), reverse=True)
	total = 0
	num = None
	curr = None
	for i in values:
		if i == num:
			curr -= 1
		else:
			num = i
			if curr is not None and i >= curr:
				curr -= 1
			else:
				curr = i
		total += curr
		if curr == 0:
			break
	res.append(str(total))
print('\n'.join(res))


import bisect
import decimal
from decimal import Decimal
import os
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate
decimal.getcontext().prec = 46

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

def getFactors(n):
	factors = []
	i = 1
	while i <= math.sqrt(n):
		if n % i == 0:
			if n // i == i:
				factors.append(i)
			else:
				factors.append(i)
				factors.append(n // i)
		i = i + 1
	return factors

def modefiedSieve():
	mx = 10 ** 7 + 1
	sieve = [-1] * mx
	for i in range(2, mx):
		if sieve[i] == -1:
			sieve[i] = i
			for j in range(i * i, mx, i):
				if sieve[j] == -1:
					sieve[j] = i
	return sieve

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

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

def sort_dict(key_value):
	return sorted(key_value.items(), key=lambda kv: (kv[1], kv[0]))

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

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

def string_list():
	return list(input())

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

def binaryToDecimal(n):
	return int(n, 2)

def DFS(n, s, adj):
	visited = [False for i in range(n + 1)]
	stack = []
	stack.append(s)
	while len(stack):
		s = stack[-1]
		stack.pop()
		if not visited[s]:
			visited[s] = True
		for node in adj[s]:
			if not visited[node]:
				stack.append(node)

def maxSubArraySum(a, size):
	maxint = 10 ** 10
	max_so_far = -maxint - 1
	max_ending_here = 0
	for i in range(0, size):
		max_ending_here = max_ending_here + a[i]
		if max_so_far < max_ending_here:
			max_so_far = max_ending_here
		if max_ending_here < 0:
			max_ending_here = 0
	return max_so_far

def solve():
	n = int(input())
	arr = list_input()
	occur = {}
	for i in arr:
		try:
			occur[i] += 1
		except KeyError:
			occur[i] = 1
	occur = list(occur.values())
	occur.sort(reverse=True)
	prev = occur[0]
	ans = occur[0]
	for i in range(1, len(occur)):
		if occur[i] < prev:
			ans += occur[i]
			prev = occur[i]
		else:
			prev -= 1
			ans += prev
		if prev == 0:
			break
	print(ans)
t = 1
t = int(input())
for _ in range(t):
	solve()


import os
import operator
import sys
from _collections import defaultdict
import bisect
from io import BytesIO, IOBase

def inar():
	return [int(k) for k in input().split()]

def power(x, p, m):
	res = 1
	while p:
		if p & 1:
			res = res * x % m
		x = x * x % m
		p >>= 1
	return res
visited = []
level = []
adj = defaultdict(list)

def bfs(node):
	global visited, level, adj
	qu = []
	visited[node] = 1
	qu.append(node)
	while qu:
		el = qu.pop(0)
		for child in adj[el]:
			if not visited[child]:
				level[child] = level[el] + 1
				visited[child] = 1
				qu.append(child)

def main():
	for _ in range(int(input())):
		n = int(input())
		arr = inar()
		freq = defaultdict(int)
		for i in range(n):
			freq[arr[i]] += 1
		freq = dict(sorted(freq.items(), key=operator.itemgetter(1)))
		ans = 0
		c = 0
		ls = list(freq.values())
		ls.sort(reverse=True)
		for i in range(len(ls)):
			if i == 0:
				ans = ls[i]
				c = ls[i]
				continue
			if c == 0:
				break
			if c - 1 <= ls[i]:
				ans += c - 1
				c = c - 1
			else:
				ans += ls[i]
				c = ls[i]
		print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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


from sys import stdin, stdout
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	d = {}
	r = [[0, 0] for i in range(n + 1)]
	for i in range(n):
		(a, b) = map(int, input().split())
		d[a] = d.get(a, 0) + 1
		r[a][b] += 1
	b = []
	for i in d.keys():
		b.append([r[i][1], i])
	b.sort(reverse=True)
	ans = 0
	s = set()
	x = 0
	for i in range(len(b)):
		while d[b[i][1]] > 0 and d[b[i][1]] in s:
			d[b[i][1]] -= 1
		x += min(r[b[i][1]][1], d[b[i][1]])
		ans += d[b[i][1]]
		s.add(d[b[i][1]])
	stdout.write(f'{ans} {x}\n')


import sys

class DCandyBoxEasyVersion:

	def solve(self):
		q = int(input())
		for _ in range(q):
			n = int(input())
			a = [int(_) for _ in input().split()]
			d = {key: 0 for key in a}
			for x in a:
				d[x] += 1
			rev_d = {key: 0 for key in d.values()}
			for x in d:
				rev_d[d[x]] += 1
			v = [x for x in rev_d]
			v.sort()
			cur = max(rev_d)
			cnt = max(rev_d)
			ans = 0
			while 1:
				if cnt == 0 or cur == 0:
					break
				if cur > cnt:
					cur -= 1
					continue
				if cnt not in rev_d or rev_d[cnt] == 0:
					cnt -= 1
					continue
				rev_d[cnt] -= 1
				ans += cur
				cur -= 1
			print(ans)
solver = DCandyBoxEasyVersion()
input = sys.stdin.readline
solver.solve()


from sys import stdin, stdout
ii = lambda : int(stdin.readline())
mi = lambda : map(int, stdin.readline().strip().split())
li = lambda : list(mi())
q = ii()
while q > 0:
	n = ii()
	cnt = [0] * (n + 1)
	a = li()
	for x in a:
		cnt[x] += 1
	cnt.sort()
	ans = 0
	take = n
	i = n
	while i > 0 and take > 0:
		if cnt[i] >= take:
			ans += take
			i -= 1
		take -= 1
	stdout.write(str(ans) + '\n')
	q -= 1


q = int(input())
for _ in range(q):
	n = [0 for _ in range(int(input()))]
	for i in list(map(int, input().split())):
		n[i - 1] += 1
	n = [x for x in n if x]
	n.sort(reverse=True)
	S = i = n.pop(0)
	while i > 0 and len(n) > 0:
		i -= 1
		i = min(i, n.pop(0))
		S += i
	print(S)


from sys import stdin
input = stdin.buffer.readline
from collections import defaultdict
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	d = defaultdict(int)
	s = set()
	for i in a:
		d[i] += 1
	for (k, v) in d.items():
		if v in s:
			while v in s and v > 0:
				v -= 1
		s.add(v)
	print(sum(s))


import sys

def f(tup):
	return tup[1]
q = int(sys.stdin.readline())
for i in range(q):
	n = int(input())
	ls = list(map(int, sys.stdin.readline().split()))
	ls.sort()
	l = [[ls[0], 1]]
	for z in range(1, len(ls)):
		k = ls[z]
		if l[-1][0] == k:
			l[-1][1] += 1
		else:
			l.append([k, 1])
	l.sort(key=f, reverse=True)
	ans = l[0][1]
	small = ans
	for z in range(1, len(l)):
		s = l[z][1]
		if s < small:
			ans += s
			small = s
		else:
			to = small - 1
			if to <= s and to > 0:
				ans += to
				small = to
		if small == 1:
			break
	sys.stdout.write(str(ans) + '\n')


import sys
from collections import Counter
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	d = Counter(arr)
	x = list(d.values())
	x.sort()
	res = x[-1]
	count = x.pop()
	while count > 0 and x:
		count = min(count - 1, x.pop())
		res += count
	print(res)


t = int(input())
for i in range(t):
	n = int(input())
	b = [0] * n
	for i in map(int, input().split()):
		b[i - 1] += 1
	b = sorted(b, reverse=True)
	c = 0
	for i in range(1, len(b)):
		if b[i] - b[i - 1] >= 0:
			b[i] = b[i - 1] - 1
	for i in b:
		if i > 0:
			c += i
		else:
			break
	print(c)


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = [0] * (n + 1)
	c = []
	for i in range(n):
		b[a[i]] += 1
	b.sort(reverse=True)
	last = n + 1
	for j in range(n + 1):
		if last == 0 or b[j] == 0:
			break
		if b[j] >= last and last != 0:
			c.append(last - 1)
			last -= 1
		else:
			c.append(b[j])
			last = b[j]
	print(sum(set(c)))


from collections import Counter
answer = []
for _ in range(int(input())):
	input()
	cnt = Counter(input().split())
	amts = [-(1 << 20), 1 << 20]
	for (_, k) in cnt.most_common():
		amts.append(max(0, min(amts[-1] - 1, k)))
	answer.append(str(sum(amts)))
print('\n'.join(answer))


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

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

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

def sin():
	return input()

def inin():
	return int(input())
for _ in range(inin()):
	n = inin()
	a = ain()
	d = dd(int)
	for i in a:
		d[i] += 1
	l = list(d.values())
	le = len(l)
	l.sort(reverse=True)
	cur = 10 ** 10
	ans = 0
	for s in l:
		m = min(cur, s)
		ans += m
		cur = m - 1
		if cur == 0:
			break
	print(ans)


from collections import defaultdict
from sys import stdin
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	d = defaultdict(int)
	for i in a:
		d[i] += 1
	d = sorted(d.values(), reverse=True)
	ld = len(d)
	s = d[0]
	m = s - 1
	for i in d[1:]:
		if m != 0:
			if i >= m:
				s += m
				m -= 1
			elif m > 0:
				s += i
				m = i - 1
		else:
			break
	print(s)


import heapq
q = int(input())
for i in range(q):
	n = int(input())
	a = [int(i) for i in input().split()]
	dic = {}
	count = 1
	lastsize = 0
	for i in range(n):
		if a[i] in dic.keys():
			dic[a[i]] += 1
		else:
			dic[a[i]] = 1
	arr = list(dic.values())
	arr.sort(reverse=True)
	lastsize = arr[0] + 1
	size = 0
	n = len(arr)
	for i in range(n):
		if lastsize == 1:
			break
		x = arr[i]
		if lastsize > x:
			lastsize = x
			size += x
		else:
			lastsize -= 1
			size += lastsize
	print(size)


from collections import Counter
ans = []
for qq in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	x = Counter(arr)
	y = list(x.values())
	y = list(reversed(sorted(y)))
	l = []
	for i in y:
		if len(l) > 0 and i in l:
			if l[-1] - 1 > 0:
				l.append(l[-1] - 1)
			else:
				break
		else:
			l.append(i)
	ans.append(sum(l))
for i in ans:
	print(i)


q = int(input())
for j in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	counter = [0] * (n + 1)
	for i in range(n):
		counter[a[i]] += 1
	counter = sorted(counter)
	ans = counter[n]
	count = counter[n]
	for i in range(n - 1, -1, -1):
		if count <= 0:
			break
		if counter[i] >= count:
			count -= 1
		if counter[i] < count:
			count = counter[i]
		ans += count
	print(ans)


from collections import defaultdict
import sys

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

def solution():
	n = int(input())
	a = list(map(int, input().split()))
	d = defaultdict(int)
	for v in a:
		d[v] += 1
	que = [value for value in d.values()]
	que.sort()
	ans = 0
	goodvalue = que[-1]
	while que and goodvalue > 0:
		count = que.pop()
		if count >= goodvalue:
			ans += goodvalue
			goodvalue = goodvalue - 1
		elif count < goodvalue:
			ans += count
			goodvalue = count - 1
	print(ans)
	return

def main():
	test = int(input())
	for i in range(test):
		solution()
	return
main()


T = int(input())
test = 0
while test < T:
	N = int(input())
	arr = input()
	arr = [int(num) for num in arr.split(' ')]
	freq = {}
	for num in arr:
		if num not in freq:
			freq[num] = 1
		else:
			freq[num] += 1
	res = 0
	k = list(freq.values())
	k.sort(reverse=True)
	m = max(k)
	idx = 0
	while m > 0 and idx < len(k):
		m = min(m, k[idx])
		res += m
		m -= 1
		idx += 1
	print(res)
	test += 1


test = int(input())
for i in range(test):
	n = int(input())
	ls = list(map(int, input().split()))
	d = {}
	for j in range(n):
		if ls[j] in d.keys():
			d[ls[j]] = d[ls[j]] + 1
		else:
			d[ls[j]] = 1
	k = set()
	s = 0
	for (key, value) in d.items():
		while value in k and value > 0:
			value = value - 1
		k.add(value)
	print(str(sum(k)))


q = int(input())
for _ in range(q):
	n = int(input())
	a = sorted(list(map(int, input().split())))
	s = []
	last = a[0]
	count = 1
	for i in range(1, n):
		if a[i] != last:
			s.append(count)
			last = a[i]
			count = 0
		count += 1
	s.append(count)
	s.sort()
	answer = s[-1]
	for i in range(len(s) - 2, -1, -1):
		if s[i] >= s[i + 1]:
			s[i] = s[i + 1] - 1
		if not s[i]:
			break
		answer += s[i]
	print(answer)


from sys import stdin, stdout
from collections import Counter
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	l = map(int, stdin.readline().split())
	a = dict(Counter(l))
	v = list(a.values())
	v.sort()
	v = v[::-1]
	i = 0
	if len(v) == 1:
		stdout.write(str(v[0]) + '\n')
		continue
	while i < len(v) - 1:
		if v[i] < v[i + 1] and v[i] != 0:
			v[i + 1] = v[i] - 1
		if v[i] < v[i + 1] and v[i] == 0:
			v[i + 1] = 0
		if v[i] == v[i + 1] and v[i + 1] != 0:
			v[i + 1] -= 1
		i += 1
	stdout.write(str(sum(v)) + '\n')


from sys import stdin, stdout
for f in range(int(stdin.readline())):
	junk = int(stdin.readline())
	data = [int(i) for i in stdin.readline().split()]
	dic = [0] * (junk + 1)
	for d in data:
		dic[d] += 1
	dic.sort(reverse=True)
	ret = 0
	curr = dic[0] + 1
	for a in dic:
		if a < curr:
			curr = a
		else:
			curr -= 1
		ret += curr
		if curr == 1 or a == 0:
			break
	stdout.write(str(ret) + '\n')


import sys
import math
from collections import defaultdict, deque
import heapq
q = int(sys.stdin.readline())
for _ in range(q):
	n = int(sys.stdin.readline())
	dic = defaultdict(list)
	for i in range(n):
		(a, b) = map(int, sys.stdin.readline().split())
		if dic[a] == []:
			dic[a] = [0, 0]
		dic[a][0] += 1
		dic[a][1] += 1 - b
	ans = 0
	cnt = 0
	heap = []
	heapq.heapify(heap)
	vis = defaultdict(int)
	for i in dic:
		heapq.heappush(heap, [-dic[i][0], dic[i][1]])
	maxlen = n
	while heap and maxlen > 0:
		(a, b) = heapq.heappop(heap)
		if vis[-a] == 1:
			heapq.heappush(heap, [a + 1, max(b - 1, 0)])
		else:
			vis[-a] = 1
			maxlen = -a - 1
			ans += -a
			cnt += b
	print(ans, ans - cnt)


def addInDict(x, y):
	global d, d2
	if x not in d:
		d[x] = 0
	if x not in d2[y]:
		d2[y][x] = 0
	d[x] += 1
	d2[y][x] += 1

def calcSum1():
	global d, d2, d3, d4, d4Keys, s1, s2
	for kol in d4Keys:
		for numPart in d4[kol]:
			kol1 = d[numPart]
			while kol1 in d3 and kol1 > 0:
				kol1 -= 1
			if kol1 > 0:
				d3[kol1] = 1
				s1 += kol1
				s2 += min(kol, kol1)
				if numPart in d2[0]:
					del d2[0][numPart]

def calcSum0():
	global d, d2, d3, s1, s2
	for key in d2[0]:
		kol = d[key]
		while kol in d3 and kol > 0:
			kol -= 1
		if kol > 0:
			d3[kol] = 1
			s1 += kol
import sys
for _ in range(int(input())):
	n = int(sys.stdin.readline())
	(d, d2, d3, d4) = ({}, {}, {}, {})
	d2[0] = {}
	d2[1] = {}
	for __ in range(n):
		(a, f) = map(int, sys.stdin.readline().split())
		addInDict(a, f)
	(s1, s2) = (0, 0)
	for i in d2[1]:
		if d2[1][i] not in d4:
			d4[d2[1][i]] = {}
		d4[d2[1][i]][i] = i
	d4Keys = list(d4.keys())
	d4Keys.sort(reverse=True)
	calcSum1()
	calcSum0()
	print(s1, s2)


q = int(input())
for _ in range(q):
	n = int(input())
	P = [0] * (n + 1)
	A = [int(x) for x in input().split()]
	for i in A:
		P[i] += 1
	P.sort(reverse=True)
	C = [P[0]]
	for i in P[1:]:
		if i == 0 or C[-1] == 1:
			break
		if i >= C[-1]:
			C.append(C[-1] - 1)
		else:
			C.append(i)
	print(sum(C))


a = []
for q in range(int(input())):
	n = int(input())
	arr = sorted([int(s) for s in input().split()])
	arr1 = []
	(count, last) = (0, arr[0])
	for i in arr:
		if last == i:
			count += 1
		else:
			arr1.append(count)
			last = i
			count = 1
	arr1.append(count)
	arr = sorted(arr1)
	(ans, last) = (0, arr[len(arr) - 1] + 1)
	for i in range(len(arr) - 1, -1, -1):
		if last == 1:
			break
		if arr[i] < last:
			last = arr[i]
		else:
			last = min(arr[i], last - 1)
		ans += last
	a.append(ans)
for i in a:
	print(i)


from sys import stdin, stdout
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	d = {}
	for i in a:
		d[i] = d.get(i, 0) + 1
	ans = 0
	b = list(d.values())
	b.sort()
	ans = 0
	s = set()
	for i in range(len(b)):
		while b[i] > 0 and b[i] in s:
			b[i] -= 1
		ans += b[i]
		s.add(b[i])
	stdout.write(str(ans) + '\n')


from collections import Counter
q = int(input())
for i in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	d = Counter(a)
	l = []
	for i in d:
		l.append(d[i])
	l.sort(reverse=True)
	ans = l[0]
	for i in range(1, len(l)):
		if l[i] >= l[i - 1]:
			l[i] = l[i - 1] - 1
		if l[i] > 0:
			ans += l[i]
		elif l[i] <= 0:
			break
	print(ans)


from collections import Counter
from sys import *
for _ in range(int(input())):
	n = int(stdin.readline())
	l = list(map(int, stdin.readline().rstrip().split()))
	c = Counter(l)
	s = list(set(l))
	s.sort(reverse=True)
	k = set()
	for x in s:
		if c[x] not in k:
			k.add(c[x])
		else:
			j = c[x]
			for y in range(j, -1, -1):
				if y in k:
					pass
				else:
					k.add(y)
					break
	print(sum(k))


t = int(input())
for o in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	b = [0] * max(a)
	d = 0
	for i in a:
		b[i - 1] += 1
	b.sort()
	b = b[::-1]
	m = b[0]
	cnt = b[0]
	for i in range(1, len(b)):
		if b[i] >= m:
			b[i] = b[i - 1] - 1
			b[i] = max(0, b[i])
		m = b[i]
		cnt += b[i]
	print(cnt)


import sys
input = sys.stdin.readline
Q = int(input())
for _ in range(Q):
	N = int(input())
	A = [int(a) for a in input().split()]
	X = {}
	for a in A:
		if a in X:
			X[a] += 1
		else:
			X[a] = 1
	Y = []
	for x in X:
		Y.append(X[x])
	Y = sorted(Y)[::-1]
	prev = Y[0] + 1
	su = 0
	for i in range(len(Y)):
		ne = min(prev - 1, Y[i])
		if ne <= 0:
			break
		su += ne
		prev = ne
	print(su)


n = int(input())
while n > 0:
	n = n - 1
	nn = int(input())
	a = [int(i) for i in input().split()]
	a.sort()
	count = [[a[0], 1]]
	num = 0
	for i in range(nn - 1):
		if count[num][0] != a[i + 1]:
			count.append([a[i + 1], 1])
			num += 1
		else:
			count[num][1] += 1
	count.sort(key=lambda i: -i[1])
	output = last = count[0][1]
	for i in range(1, len(count)):
		if last <= count[i][1]:
			if last != 0:
				output = output + last - 1
				last = last - 1
		else:
			output = output + count[i][1]
			last = count[i][1]
	print(output)


import sys
input = sys.stdin.readline
import collections as cc
n = int(input())
for tc in range(n):
	n = int(input())
	A = cc.Counter(map(int, input().split()))
	S = sorted(A.values(), reverse=True)
	N = 10 ** 10
	ans = 0
	for s in S:
		M = min(N, s)
		ans += M
		N = M - 1
		if N == 0:
			break
	print(ans)


from sys import stdin, stdout
q = int(input())
for i in range(q):
	n = int(input())
	l = []
	a = [int(x) - 1 for x in stdin.readline().split()]
	for _ in [0] * n:
		l.append(0)
	for j in a:
		l[j] += 1
	l.sort(reverse=True)
	naj = l[0]
	ans = l[0]
	for j in range(1, n):
		if l[j] >= naj:
			naj -= 1
			ans += naj
		else:
			naj = l[j]
			ans += l[j]
		if l[j] == 0 or naj <= 0:
			break
	stdout.write(f'{ans}\n')


from collections import Counter
t = int(input())
while t > 0:
	n = int(input())
	l = list(map(int, input().split()))
	if n == 1:
		print(1)
		t -= 1
		continue
	c = Counter(l)
	c1 = c.values()
	l = list(c1)
	l.sort()
	test = 0
	i = l[-1]
	r = len(l)
	j = r - 1
	s = 0
	k = l
	while j > -1:
		if l[j] >= i:
			j -= 1
			s += i
			i -= 1
		else:
			s += l[j]
			i = l[j] - 1
			j -= 1
		if i < 1:
			break
	print(s)
	t -= 1


from sys import stdin, stdout
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	v = stdin.readline().split(' ')
	freq = [0] * (n + 2)
	for x in v:
		freq[int(x)] += 1
	freq.sort(reverse=True)
	lst = int(1000000000.0)
	s = 0
	for i in freq:
		if i < lst:
			lst = i
		if lst > 0:
			s += lst
		lst -= 1
	print(s)


import sys
from collections import Counter
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	cnt = Counter(map(int, input().split()))
	cnt = Counter(cnt.values())
	ans = 0
	for i in range(n, 0, -1):
		if i not in cnt or cnt[i] == 1:
			continue
		cnt[i - 1] += cnt[i] - 1
	print(sum(cnt.keys()))


q = int(input())
for _ in range(q):
	n = int(input())
	gifts = map(int, input().split())
	candyDict = {}
	for i in gifts:
		try:
			candyDict[i] += 1
		except:
			candyDict[i] = 1
	xd = list(candyDict.values())
	xd.sort()
	toCheck = max(xd)
	total = 0
	for i in range(len(xd) - 1, -1, -1):
		if toCheck > 0:
			tmp = min(xd[i], toCheck)
			total += tmp
			toCheck = tmp - 1
		else:
			break
	print(total)


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, copy, functools
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
mod2 = 998244353
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

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

def LLI():
	return [list(map(int, l.split())) for l in sys.stdin.readlines()]

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

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

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

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def pe(s):
	return print(str(s), file=sys.stderr)

def JA(a, sep):
	return sep.join(map(str, a))

def JAA(a, s, t):
	return s.join((t.join(map(str, b)) for b in a))

def IF(c, t, f):
	return t if c else f

def YES(c):
	return IF(c, 'YES', 'NO')

def Yes(c):
	return IF(c, 'Yes', 'No')

def main():
	t = I()
	rr = []
	for _ in range(t):
		n = I()
		a = LI()
		c = collections.Counter(a)
		u = sorted(c.values(), reverse=True)
		m = inf
		r = 0
		for s in u:
			if s >= m:
				s = m - 1
				if s < 1:
					break
			r += s
			m = s
		rr.append(r)
	return JA(rr, '\n')
print(main())


from sys import stdin, stdout
input = stdin.readline
from collections import Counter
p = int(input())
for i in range(0, p):
	n = int(input())
	a = list(map(int, input().split()))
	k = Counter(a)
	k = list(k.values())
	k.sort(reverse=True)
	for j in range(len(k) - 1):
		if k[j] <= k[j + 1]:
			k[j + 1] = max(k[j] - 1, 0)
	print(sum(k))


q = int(input())
for _ in range(q):
	n = int(input())
	a = [int(x) for x in input().split()]
	d = {}
	for x in a:
		if x not in d:
			d[x] = 1
		else:
			d[x] += 1
	thing = sorted(d.values(), reverse=True)
	sum = thing[0]
	for i in range(1, len(thing)):
		if thing[i] > thing[i - 1] - 1:
			thing[i] = thing[i - 1] - 1
		if thing[i] < 0:
			thing[i] = 0
		sum += thing[i]
	print(sum)


for i in range(int(input())):
	n = int(input())
	ar = input().split()
	arr = dict()
	for k in ar:
		if arr.get(k) == None:
			arr[k] = 0
		arr[k] += 1
	s = []
	for l in arr:
		s.append(arr[l])
	s = sorted(s)
	q = s[len(s) - 1]
	sumy = q
	for k in range(len(s) - 2, -1, -1):
		if q > s[k]:
			sumy += max(s[k], 0)
			q = s[k]
		else:
			sumy += max(q - 1, 0)
			q -= 1
		if q <= 0:
			break
	print(sumy)


t = int(input())
while t:
	t -= 1
	n = int(input())
	ar = list(map(int, input().split()))
	d = {}
	for i in ar:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	br = set()
	for i in d:
		if d[i] in br:
			counter = 1
			while d[i] - counter > 0:
				if d[i] - counter not in br:
					br.add(d[i] - counter)
					break
				counter += 1
		elif d[i] not in br:
			br.add(d[i])
	print(sum(br))


import sys
input = sys.stdin.readline

def ecount(X):
	(c, ans) = (1, [])
	for i in range(len(X) - 1):
		if X[i] == X[i + 1]:
			c += 1
		else:
			ans.append(c)
			c = 1
	ans.append(c)
	return ans
for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	b = ecount(a)
	b.sort(reverse=1)
	ans = b[0]
	m = b[0]
	for i in b[1:]:
		m = min(max(0, m - 1), i)
		ans += m
	print(ans)


q = int(input())
for _ in range(q):
	n = int(input())
	a = [int(x) for x in input().split()]
	arr = [0] * n
	for i in a:
		arr[i - 1] += 1
	arr.sort(reverse=True)
	s = arr[0]
	prev = arr[0]
	for i in range(1, len(arr)):
		if prev == 1:
			break
		if arr[i] < prev:
			s = s + arr[i]
			prev = arr[i]
		else:
			prev = prev - 1
			s = s + prev
		if arr[i] == 0:
			break
	print(s)


from collections import defaultdict
from heapq import *
from sys import stdin, stdout
q = int(stdin.readline())
for it in range(q):
	n = int(stdin.readline())
	d = [0] * n
	f = [0] * n
	for i in range(n):
		(t, b) = map(int, stdin.readline().split())
		d[t - 1] += 1
		if b == 1:
			f[t - 1] += 1
	d = [(x, i) for (i, x) in enumerate(d)]
	d.sort(reverse=True)
	h = []
	ans = 0
	ans_f = 0
	cur = n
	idx = 0
	while cur > 0:
		while idx < len(d) and d[idx][0] == cur:
			d1 = d[idx]
			heappush(h, (-f[d1[1]], d1[1]))
			idx += 1
		if h:
			ans += cur
			e = heappop(h)
			ans_f += min(cur, -e[0])
		cur -= 1
	stdout.write(str(ans) + ' ' + str(ans_f) + '\n')


def main():
	t = int(input())
	for T in range(t):
		n = int(input())
		a = [int(x) for x in input().split()]
		count = []
		from collections import defaultdict as dd
		d = dd(int)
		for i in range(n):
			d[a[i]] += 1
		l = d.keys()
		for i in l:
			count.append(d[i])
		count.sort(reverse=True)
		for i in range(len(count) - 1):
			if count[i] <= count[i + 1]:
				count[i + 1] = max(count[i] - 1, 0)
		print(sum(count))
main()


from collections import deque as de
import math
from math import sqrt as sq
from math import floor as fl
from math import ceil as ce
from sys import stdin, stdout
import re
from collections import Counter as cnt
from functools import reduce
from itertools import groupby as gb
from bisect import bisect_left as bl, bisect_right as br

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

class My_stack:

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

	def my_push(self, x):
		return self.data.append(x)

	def my_pop(self):
		return self.data.pop()

	def my_peak(self):
		return self.data[-1]

	def my_contains(self, x):
		return self.data.count(x)

	def my_show_all(self):
		return self.data

	def isEmpty(self):
		return len(self.data) == 0
arrStack = My_stack()

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

def binarytodecimal(n):
	return int(n, 2)

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def get_prime_factors(number):
	prime_factors = []
	while number % 2 == 0:
		prime_factors.append(2)
		number = number / 2
	for i in range(3, int(math.sqrt(number)) + 1, 2):
		while number % i == 0:
			prime_factors.append(int(i))
			number = number / i
	if number > 2:
		prime_factors.append(int(number))
	return prime_factors

def get_frequency(list):
	dic = {}
	for ele in list:
		if ele in dic:
			dic[ele] += 1
		else:
			dic[ele] = 1
	return dic

def Log2(x):
	return math.log10(x) / math.log10(2)

def getProduct(n):
	product = 1
	while n != 0:
		product = product * (n % 10)
		n = n // 10
	return product

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

def isPowerOfTwo(n):
	return math.ceil(Log2(n)) == math.floor(Log2(n))

def checkisap(list):
	d = list[1] - list[0]
	for i in range(2, len(list)):
		temp = list[i] - list[i - 1]
		if temp != d:
			return False
	return True

def primes_method5(n):
	out = {}
	sieve = [True] * (n + 1)
	for p in range(2, n + 1):
		if sieve[p]:
			out[p] = 1
			for i in range(p, n + 1, p):
				sieve[i] = False
	return out

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

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

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

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

def si():
	return list(map(str, input()))

def indict():
	dic = {}
	for (index, value) in enumerate(input().split()):
		dic[int(value)] = int(index) + 1
	return dic

def frqdict():
	dic = {}
	for (index, value) in enumerate(input()):
		if value not in dic:
			dic[value] = 1
		else:
			dic[value] += 1
	return dic
q = ii()
while q:
	q -= 1
	n = ii()
	a = li()
	dic = get_frequency(a)
	ll = sorted(list(dic.values()), reverse=True)
	ans = ll[0]
	curr = ans - 1
	for i in range(1, len(ll)):
		if ll[i] <= curr:
			ans += ll[i]
			curr = ll[i] - 1
		else:
			ans += max(curr, 0)
			curr -= 1
	print(ans)


t = int(input())
r = []
for _ in range(t):
	(cnt, rng, res) = ({}, {}, set())
	n = int(input())
	arr = list(map(int, input().split()))
	for i in arr:
		if i in cnt:
			cnt[i] += 1
		else:
			cnt[i] = 1
	for i in cnt.values():
		if i in rng:
			rng[i] += 1
		else:
			rng[i] = 1
	for it in sorted(rng.keys(), reverse=True):
		(i, j) = (it, 0)
		while i > 0 and j < rng[it]:
			if len(res) > 0 and min(res) <= i:
				i -= 1
				continue
			res.add(i)
			i -= 1
			j += 1
	r.append(sum(res))
print('\n'.join(map(str, r)))


for q in range(int(input())):
	n = int(input())
	A = list(map(int, input().split()))
	G = {}
	for i in A:
		if i not in G:
			G[i] = 0
		G[i] += 1
	B = []
	for i in G:
		B.append(G[i])
	B.sort(reverse=True)
	cnt = 0
	op = B[0] + 1
	for i in B:
		if i >= op:
			op -= 1
			cnt += max(0, op)
		else:
			op = i
			cnt += i
		if op == 0:
			break
	print(cnt)


import sys
q = int(sys.stdin.readline())
ans_arr = []
for x in range(q):
	n = int(sys.stdin.readline())
	a = [int(i) for i in sys.stdin.readline().split()]
	a.sort()
	arr = []
	prev = -2
	ind = -1
	for x in range(n):
		if a[x] != prev:
			arr.append(1)
			ind += 1
		else:
			arr[ind] += 1
		prev = a[x]
	arr.sort()
	answer = 0
	last = arr[-1] + 1
	for g in range(len(arr) - 1, -1, -1):
		val = max(0, min(last - 1, arr[g]))
		answer += val
		last = val
	ans_arr.append(str(answer))
print('\n'.join(ans_arr))


t = int(input())
for _ in range(0, t):
	n = int(input())
	l = list(map(int, input().split()))
	g = max(l)
	a = [0] * (g + 1)
	for i in l:
		a[i] = a[i] + 1
	k = list()
	for i in a:
		if i > 0:
			k.append(i)
	k.sort()
	m = k[-1]
	s = m
	f = len(k)
	if f == 1:
		print(k[0])
		continue
	for i in range(f - 2, -1, -1):
		if k[i] >= m:
			k[i] = m - 1
			m = m - 1
		else:
			m = k[i]
		s = s + m
		if m <= 0:
			break
	print(s)


for f in range(int(input())):
	junk = input()
	data = [int(i) for i in input().split()]
	dic = {}
	for d in data:
		if d in dic:
			dic[d] += 1
		else:
			dic[d] = 1
	array = sorted(dic.values(), reverse=True)
	ret = 0
	curr = array[0] + 1
	for a in array:
		if a < curr:
			curr = a
		else:
			curr -= 1
		ret += curr
		if curr == 1:
			break
	print(ret)


q = int(input())
L = lambda : list(map(int, input().split()))
for quer in range(q):
	n = int(input())
	a = L()
	c = [0] * (n + 1)
	for i in a:
		c[i] += 1
	c.sort(reverse=True)
	mx = n + 1
	ans = 0
	for i in c:
		if i > 0 and mx > 1:
			if i < mx:
				ans += i
				mx = i
			else:
				ans += mx - 1
				mx -= 1
	print(ans)


import sys
input = sys.stdin.readline
from collections import Counter
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	d = Counter(a)
	s = sorted(d, key=lambda x: -d[x])
	upper_limit = float('inf')
	ans = 0
	for i in s:
		if upper_limit == float('inf'):
			ans += d[i]
			upper_limit = d[i]
		else:
			if upper_limit <= 1:
				break
			ans += min(d[i], upper_limit - 1)
			upper_limit = min(d[i], upper_limit - 1)
	print(ans)


import sys
input = sys.stdin.readline
m = int(input())
for ii in range(m):
	n = int(input())
	l = list(map(int, input().split()))
	s = [0 for _ in range(n)]
	for x in l:
		s[x - 1] += 1
	s = sorted(s)
	s.reverse()
	for i in range(1, n):
		if s[i] >= s[i - 1]:
			s[i] = max(s[i - 1] - 1, 0)
	print(sum(s))


import collections as cl
ans = []
for _ in range(int(input())):
	(n, a) = (input(), list(sorted(cl.Counter(input().split()).values(), reverse=True)))
	summ = last = a[0]
	for i in range(1, len(a)):
		if last == 1:
			break
		last = min(last - 1, a[i])
		summ += last
	ans.append(str(summ))
print('\n'.join(ans))


from sys import stdin, stdout
from collections import Counter
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	d = Counter(a)
	s = set()
	ans = 0
	b = sorted(d.values())
	mx = b[-1]
	for i in range(len(b) - 1, -1, -1):
		if mx == 0:
			break
		ans += min(b[i], mx)
		mx = min(b[i], mx) - 1
	print(ans)


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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import Counter
import heapq
for i in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	c = Counter(arr)
	ls = list(c.values())
	ls.sort(reverse=True)
	ans = 0
	d = {}
	ma = ls[0]
	for i in range(len(ls)):
		if ls[i] not in d:
			ans += ls[i]
			d[ls[i]] = 1
		else:
			val = max(0, min(ma - 1, ls[i] - 1))
			ans += val
			d[val] = 1
			ma = val
	print(ans)


def merge(arr, l, m, r):
	n1 = m - l + 1
	n2 = r - m
	L = [0] * n1
	R = [0] * n2
	for i in range(0, n1):
		L[i] = arr[l + i]
	for j in range(0, n2):
		R[j] = arr[m + 1 + j]
	i = 0
	j = 0
	k = l
	while i < n1 and j < n2:
		if L[i] <= R[j]:
			arr[k] = L[i]
			i += 1
		else:
			arr[k] = R[j]
			j += 1
		k += 1
	while i < n1:
		arr[k] = L[i]
		i += 1
		k += 1
	while j < n2:
		arr[k] = R[j]
		j += 1
		k += 1

def mergeSort(arr, l, r):
	if l < r:
		m = (l + (r - 1)) // 2
		mergeSort(arr, l, m)
		mergeSort(arr, m + 1, r)
		merge(arr, l, m, r)
t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	count = [0] * n
	for j in range(n):
		count[arr[j] - 1] += 1
	realCount = []
	for j in range(n):
		if count[j] != 0:
			realCount.append(count[j])
	l = len(realCount)
	mergeSort(realCount, 0, l - 1)
	answer = [realCount[-1]]
	ans = 0
	for j in range(2, l + 1):
		if realCount[-j] >= answer[-1]:
			if answer[-1] - 1 != 0:
				answer.append(answer[-1] - 1)
		else:
			answer.append(realCount[-j])
	print(sum(answer))


import time
q = int(input())
ans = []
start = time.time()
for i in range(q):
	n = int(input())
	a = [int(j) for j in input().split()]
	d = [0 for j in range(n)]
	for j in range(n):
		d[a[j] - 1] += 1
	d.sort(reverse=True)
	s = d[0]
	last = d[0]
	for j in range(1, n):
		if last > d[j]:
			s += d[j]
			last = d[j]
		else:
			last -= 1
			if last <= 0:
				break
			s += last
	ans.append(s)
for i in range(q):
	print(ans[i])
finish = time.time()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	l = [0] * (n + 1)
	for j in a:
		l[j] += 1
	l.sort(reverse=True)
	last = -1
	ans = 0
	vis = []
	for j in range(len(l)):
		if l[j] == 0:
			break
		if l[j] in vis:
			k = l[j]
			while k in vis and k > 0:
				k -= 1
			ans += k
			vis.append(k)
		else:
			ans += l[j]
			vis.append(l[j])
	print(ans)


t = int(input())
while t > 0:
	n = int(input())
	a = list(map(int, input().split()))
	P = (1 + n) * [0]
	for i in a:
		P[i] += 1
	b = []
	for i in range(1 + n):
		if P[i] != 0:
			b.append(P[i])
	b.sort()
	m = len(b) - 1
	ans = 0
	take = b[m]
	for i in range(m, -1, -1):
		if take < 0:
			break
		if 0 < b[i] <= take:
			ans += b[i]
			take = b[i] - 1
		elif b[i] > take:
			ans += take
			take -= 1
	print(ans)
	t -= 1


for i in ' ' * int(input()):
	n = int(input())
	d = [0] * n
	for i in map(int, input().split()):
		d[i - 1] += 1
	s = 0
	m = 10 ** 9
	d.sort(reverse=True)
	for i in d:
		m = max(min(m - 1, i), 0)
		s += m
	print(s)


from sys import stdin, stdout
q = int(input())
while q != 0:
	q -= 1
	n = int(stdin.readline())
	lt = [int(x) for x in stdin.readline().split()]
	cnt = [0] * (n + 1)
	for c in lt:
		cnt[c] += 1
	cnt.sort(reverse=True)
	(lst, ans) = (cnt[0], cnt[0])
	for i in range(1, n + 1):
		if lst == 0:
			break
		if cnt[i] < lst:
			ans += cnt[i]
			lst = cnt[i]
		else:
			lst -= 1
			ans += lst
	print(ans)


from collections import Counter
t = int(input())
ANS = []
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	freq = sorted(dict(Counter(a)).values(), reverse=True)
	i = 1
	ans = freq[0]
	last = freq[0]
	while i < len(freq):
		val = freq[i]
		if val >= last:
			val = last - 1
		if val <= 0:
			break
		else:
			ans += val
			i += 1
			last = val
	ANS.append(ans)
for i in ANS:
	print(i)


import sys
input = sys.stdin.readline
import collections
q = int(input())
for _ in range(q):
	n = int(input())
	A = [int(_) for _ in input().split()]
	AA = list(collections.Counter(A).values())
	AA.sort(reverse=True)
	Ans = [AA[0]]
	for i in range(1, len(AA)):
		a = AA[i]
		if a >= Ans[-1]:
			Ans.append(max(Ans[-1] - 1, 1))
		else:
			Ans.append(a)
	print(sum(set(Ans)))


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10 ** 8)
mod = 10 ** 9 + 7
mod1 = 998244353
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')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def func(self, a, b):
		if a[0] > b[0]:
			return a
		return b

	def __init__(self, data, default=(0, 0)):
		func = self.func
		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 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 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 powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

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

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

def count(s, n, a):
	st = 0
	end = n - 1
	ans = 0
	while st <= end:
		mid = (st + end) // 2
		if a <= s[mid]:
			ans = mid + 1
			st = mid + 1
		else:
			end = mid - 1
	return ans
for ik in range(int(input())):
	n = int(input())
	d = [[0, 0] for i in range(n + 1)]
	for i in range(n):
		(a, f) = map(int, input().split())
		d[a][0] += 1
		d[a][1] += f
	d.sort(reverse=True)
	ans = 0
	last = n * n
	for i in range(n):
		if last <= 0:
			break
		ans += min(d[i][0], last)
		last = min(d[i][0], last) - 1
	s1 = []
	e = []
	for i in range(len(d)):
		s1.append(d[i][0])
		e.append((d[i][1], i))
	s = SegmentTree1(e)
	an = 0
	for i in range(n + 1, -1, -1):
		b = count(s1, len(s1), i)
		if b == 0:
			continue
		w = s.query(0, b - 1)
		an += min(i, w[0])
		s.__setitem__(w[1], (0, w[1]))
	print(ans, an)


from collections import Counter
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	input()
	freq = sorted(Counter(input().split()).values())
	n = len(freq)
	temp = freq[n - 1]
	Sum = 0
	for i in range(n):
		Sum += max(0, min(freq[n - i - 1], temp))
		temp = min(freq[n - i - 1], temp) - 1
	print(Sum)


for q in range(int(input())):
	n = int(input())
	a = list(map(int, input().split(' ')))
	freq = {}
	for i in a:
		if i in freq:
			freq[i] += 1
		else:
			freq[i] = 1
	l = []
	for (key, value) in freq.items():
		l.append(value)
	l.sort()
	mval = l[-1]
	su = l[-1]
	for i in range(len(l) - 2, -1, -1):
		if mval > 0:
			if l[i] == mval:
				mval -= 1
				su += mval
			elif l[i] < mval:
				su += l[i]
				mval = l[i]
			else:
				mval -= 1
				su += mval
	print(su)


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

def yes():
	print('YES')

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

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

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

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

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

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

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

def main():
	try:
		n = I()
		l = list(In())
		d = dict(l)
		z = []
		for x in d:
			z.append(d[x])
		i = 0
		n1 = len(z)
		z.sort(reverse=True)
		ans = 0
		para = set()
		for x in z:
			temp = x
			while temp > 0:
				if temp not in para:
					ans += temp
					para.add(temp)
					break
				temp -= 1
		print(ans)
	except:
		pass
M = 998244353
P = 1000000007
for _ in range(I()):
	main()


from sys import stdin, stdout

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

def INL():
	return [int(_) for _ in stdin.readline().split()]

def INS():
	return stdin.readline()

def MOD():
	return pow(10, 9) + 7

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

def OPL(ans):
	[stdout.write(str(_) + ' ') for _ in ans]
	stdout.write('\n')
for _ in range(INI()):
	n = INI()
	X = sorted(INL())
	x = X[0]
	c = 0
	s = set()
	ans = 0
	add = 0
	for _ in range(n):
		if x == X[_]:
			c += 1
		else:
			ans += add
			s.add(add)
			x = X[_]
			add = 0
			c = 1
		if c not in s:
			add = c
	if add not in s:
		ans += add
	OPS(ans)


from collections import defaultdict
import operator
import collections
for j in range(int(input())):
	n = int(input())
	l1 = list(map(int, input().split()))
	d = defaultdict(int)
	for i in l1:
		d[i] += 1
	sorted_x = dict(sorted(d.items(), key=operator.itemgetter(1), reverse=True))
	l2 = []
	MIN = 100000000000
	for val in sorted_x.values():
		if MIN != 0:
			if val >= MIN:
				l2.append(MIN - 1)
				MIN = MIN - 1
			else:
				l2.append(val)
				MIN = val
	print(sum(l2))


from sys import stdin, stdout
M = lambda : list(map(int, stdin.readline().split()))
q = int(stdin.readline())
for qur in range(q):
	n = int(stdin.readline())
	C = [0] * (n + 1)
	F = [0] * (n + 1)
	for i in range(n):
		(a, f) = M()
		F[a] += f
		C[a] += 1
	C = [(C[i], F[i]) for i in range(1, n + 1)]
	C.sort(reverse=True)
	s = set()
	ans = 0
	nm = 0
	i = 0
	for mx in range(n, 0, -1):
		while i < len(C) and C[i][0] == mx:
			s.add((C[i][1], i))
			i += 1
		if len(s):
			e = max(s)
			ans += mx
			nm += min(e[0], mx)
			s.remove(e)
	stdout.write(str(ans) + ' ' + str(nm) + '\n')


import sys
input = sys.stdin.readline
from heapq import *
Q = int(input())
for _ in range(Q):
	N = int(input())
	A = []
	for __ in range(N):
		(a, f) = map(int, input().split())
		A.append((a, f))
	X = {}
	for (a, f) in A:
		if a in X:
			X[a][0] += 1
			X[a][1] += f
		else:
			X[a] = [1, f]
	Y = []
	for x in X:
		Y.append(X[x])
	Y = sorted(Y)[::-1] + [[0, 0]]
	su = 0
	suf = 0
	ne = Y[0][0]
	y = Y[0][0]
	i = 0
	h = []
	while i < len(Y):
		if len(h) == 0:
			y = Y[i][0]
			ne = min(ne, y)
		if ne < 0:
			break
		while i < len(Y) and Y[i][0] >= ne:
			heappush(h, -Y[i][1])
			i += 1
		if h:
			su += ne
			suf += min(-heappop(h), ne)
		ne -= 1
		if ne < 0:
			break
	print(su, suf)


from sys import stdin
from math import gcd, sqrt
from collections import deque
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')
hg = lambda x, y: (y + x - 1) // x * x
for _ in range(I()):
	a = [0] * I()
	for i in R():
		a[i - 1] += 1
	a.sort(reverse=True)
	sm = [a[0]]
	for i in a[1:]:
		if i >= sm[-1]:
			sm += (sm[-1] - 1,)
		else:
			sm += (i,)
		if sm[-1] == 0:
			break
	print(sum(sm))


q = int(input())
for i in range(q):
	n = int(input())
	a = [int(i) for i in input().split(' ')]
	counter = [0] * (len(a) + 1)
	for i in range(len(a)):
		counter[a[i]] += 1
	counter.sort(reverse=True)
	curr = 10 ** 9
	ans = 0
	for i in counter:
		curr = max(min(curr - 1, i), 0)
		ans += curr
	print(ans)


import sys
from collections import Counter
import itertools

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

def dinput():
	return int(input())

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

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

def main():
	input()
	q = {}
	for i in tinput():
		if i not in q:
			q[i] = 1
		else:
			q[i] = q[i] + 1
	r = []
	for i in q:
		r.append(q[i])
	r.sort()
	y = 0
	t = []
	for i in range(len(r)):
		while r[i] in t and r[i] > 0:
			r[i] -= 1
		t.append(r[i])
		y += t[i]
	print(y)
for i in range(int(input())):
	main()


q = int(input())
for _ in range(q):
	n = int(input())
	P = [0] * (n + 1)
	A = [int(x) for x in input().split()]
	for i in A:
		P[i] += 1
	P.sort(reverse=True)
	Ans = P[0]
	Expected = Ans - 1
	for i in P[1:]:
		if i and Expected:
			if i >= Expected:
				Ans += Expected
				Expected -= 1
			else:
				Ans += i
				Expected = i - 1
		else:
			break
	print(Ans)


import sys
from collections import Counter
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	c01 = []
	c1 = [0] * (n + 1)
	for (x, y) in (map(int, input().split()) for _ in range(n)):
		c01.append(x)
		if y == 1:
			c1[x] += 1
	f1cnt = [[] for _ in range(n + 1)]
	cnt01 = Counter(c01)
	for (k, v) in cnt01.items():
		f1cnt[v].append(c1[k])
	ans = 0
	ansf1 = 0
	for i in range(n, 0, -1):
		if f1cnt[i]:
			ans += i
			f1cnt[i].sort()
			ansf1 += min(i, f1cnt[i].pop())
			while f1cnt[i]:
				f1cnt[i - 1].append(f1cnt[i].pop())
	print(ans, ansf1)


from sys import stdin, stdout
input = lambda : stdin.readline()
from collections import Counter
n = int(input())
ok = [0] * n
for _ in range(n):
	p = int(input()) + 1
	ans = 0
	for i in Counter(map(int, input().split())).most_common():
		if i[1] > p:
			ans += p
			p = max(0, p - 1)
		else:
			ans += i[1]
			p = max(0, i[1] - 1)
	ok[_] = ans
stdout.write(' '.join(map(str, ok)))


q = int(input())
R = lambda : map(int, input().split())
answers = []

def solve(a):
	groupsNumber = dict()
	for groupName in a:
		if groupName in groupsNumber:
			groupsNumber[groupName] += 1
		else:
			groupsNumber[groupName] = 1
	values = list(groupsNumber.values())
	values.sort(reverse=True)
	sumResult = 0
	lastAddedValue = values[0]
	for i in range(0, len(values)):
		if i == 0:
			sumResult += lastAddedValue
			continue
		if values[i] >= lastAddedValue:
			lastAddedValue -= 1
			if lastAddedValue == 0:
				return sumResult
			sumResult += lastAddedValue
		else:
			lastAddedValue = values[i]
			sumResult += lastAddedValue
	return sumResult
for i in range(0, q):
	n = R()
	confets = list(R())
	result = solve(confets)
	answers.append(result)
[print(x) for x in answers]


q = int(input())
for _ in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	u = [0] * n
	for i in range(n):
		u[a[i] - 1] += 1
	u.sort(reverse=1)
	k = u[0]
	ans = k
	for i in range(1, n):
		if u[i] >= u[i - 1]:
			u[i] = u[i - 1] - 1
			if u[i] <= 0:
				break
		ans += u[i]
	print(ans)


q = int(input())
for j in range(q):
	n = int(input())
	d = list(map(int, input().split()))
	d.sort()
	a = [0 for i in range(d[-1] + 1)]
	for i in range(len(d)):
		a[d[i]] += 1
	a.sort()
	a = a[::-1]
	t = a[0]
	for i in range(1, len(a)):
		if a[i] < a[i - 1]:
			t += a[i]
		else:
			t += max(a[i - 1] - 1, 0)
			a[i] = a[i - 1] - 1
	print(t)


mod = 1000000007
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())
t = ii()
for _ in range(t):
	n = ii()
	l = il()
	d = dict()
	for i in l:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	l2 = sorted([d[i] for i in d], reverse=True)
	mx = l2[0]
	sm = l2[0]
	for i in l2[1:]:
		if i < mx:
			mx = i
		else:
			mx -= 1
		if mx < 0:
			mx = 0
		sm += mx
	print(sm)


import math
from collections import defaultdict
import sys
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.buffer.readline())

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

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

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def BI():
	return sys.stdin.buffer.readline().rstrip()

def SI():
	return sys.stdin.buffer.readline().rstrip().decode()

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

def lli(rows):
	return [li() for _ in range(rows)]

def si():
	return input()

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

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

def solve():
	n = ii()
	a = li()
	d = defaultdict(int)
	for i in range(n):
		d[a[i]] += 1
	all = []
	for key in d:
		all.append(d[key])
	all.sort(reverse=True)
	m = len(all)
	j = 1
	p = all[0] - 1
	while j < m:
		if all[j] >= p:
			all[j] = p
			p = p - 1 if p > 0 else 0
			j += 1
		else:
			p = all[j] - 1 if all[j] > 0 else 0
			j += 1
	return sum(all)

def main():
	for _ in range(ii()):
		sys.stdout.write(str(solve()) + '\n')
main()


q = int(input())
for _ in range(q):
	n = [0] * int(input())
	for i in list(map(int, input().split())):
		n[i - 1] += 1
	n.sort(reverse=True)
	S = 0
	curr = n[0] + 1
	for a in n:
		if a < curr:
			curr = a
		else:
			curr -= 1
		S += curr
		if curr == 1 or a == 0:
			break
	print(S)


from sys import stdin, stdout
from collections import defaultdict

def main():
	q = int(stdin.readline())
	for qi in range(q):
		n = int(stdin.readline())
		if n == 1:
			stdout.write(f'1 {stdin.readline().split()[1]}\n')
			continue
		xs = defaultdict(lambda : [0, 0])
		for _ in range(n):
			(x, f) = map(int, stdin.readline().split())
			xs[x][0] += 1
			xs[x][1] += f
		(cs, fs) = zip(*sorted(xs.values(), reverse=True))
		n_cs = len(cs)
		min_used = 300000.0
		res = 0
		fres = 0
		is_used = [False for _ in range(n_cs)]
		for (icnt, cnt) in enumerate(cs):
			if min_used == 0:
				break
			if cnt >= min_used:
				res += min_used - 1
				min_used -= 1
			else:
				res += cnt
				min_used = cnt
			(maxi, posi) = (0, -1)
			for i in range(n_cs):
				if cs[i] < min_used:
					break
				if not is_used[i] and maxi <= fs[i]:
					posi = i
					maxi = fs[i]
			fres += min(maxi, min_used)
			is_used[posi] = True
		stdout.write(f'{res} {fres}\n')
main()


from sys import stdin, stdout
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	l = list(map(int, stdin.readline().split()))
	cnt = [0] * n
	for i in l:
		cnt[i - 1] += 1
	cnt.sort(reverse=True)
	curr = int(1000000000.0)
	ans = 0
	for i in cnt:
		curr = max(min(curr - 1, i), 0)
		ans += curr
	stdout.write(str(ans) + '\n')


from collections import *
from sys import stdin, stdout
ans = []
for i in range(int(stdin.readline())):
	(n, a) = (int(input()), Counter(list(map(int, stdin.readline().split()))))
	all = sorted(a.values(), reverse=True)
	for j in range(1, len(all)):
		if all[j] >= all[j - 1]:
			all[j] = max(0, all[j - 1] - 1)
	ans.append(str(sum(all)))
stdout.write('\n'.join(ans))


q = int(input())
all_ans = []
for i in range(q):
	ans = 0
	d = {}
	n = int(input())
	s = input().split()
	for val in s:
		if val in d:
			d[val] += 1
		else:
			d[val] = 1
	set_u = set()
	for i in d.values():
		while i > 0:
			if i not in set_u:
				ans += i
				set_u.add(i)
				break
			i -= 1
	all_ans.append(ans)
for i in all_ans:
	print(i)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ma = max(a)
	lis = [0 for i in range(ma)]
	for i in a:
		lis[i - 1] = lis[i - 1] + 1
	k = set()
	count = 0
	lis.sort()
	first = lis[ma - 1]
	count = count + lis[ma - 1]
	for i in range(ma - 2, -1, -1):
		if lis[i] >= first:
			first = first - 1
			count = count + first
		else:
			first = lis[i]
			count = count + first
		if first == 0:
			break
	print(count)


(z, zz, dgraphs) = (input, lambda : list(map(int, z().split())), {})
from string import *
from collections import *
from queue import *
from sys import *
from collections import *
from math import *
from heapq import *
from itertools import *
from bisect import *
from collections import Counter as cc
from math import factorial as f

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

def prime(x):
	p = ceil(x ** 0.5) + 1
	for i in range(2, p):
		if x % i == 0 and x != 2:
			return 0
	return 1

def dfs(u, visit, graph):
	visit[u] = True
	for i in graph[u]:
		if not visit[i]:
			dfs(i, visit, graph)
num = int(z())
for i in range(num):
	n = int(z())
	l = [0] * (n + 1)
	for i in zz():
		l[i] += 1
	m = 10 ** 34
	s = 0
	l.sort(reverse=True)
	for i in l:
		m = max(min(m - 1, i), 0)
		s += m
	print(s)


from collections import defaultdict

def find(A):
	dic = defaultdict(int)
	for i in range(len(A)):
		dic[A[i]] += 1
	temp = []
	for x in dic:
		temp += [dic[x]]
	temp = sorted(temp, reverse=True)
	count = temp[0]
	MAX = temp[0]
	for i in range(1, len(temp)):
		if MAX == 1:
			break
		if temp[i] == MAX:
			MAX = temp[i] - 1
			count += MAX
		elif temp[i] > MAX:
			MAX = MAX - 1
			count += MAX
		else:
			count += temp[i]
			MAX = temp[i]
	return count
for _ in range(int(input())):
	input()
	A = list(map(int, input().strip().split(' ')))
	print(find(A))


q = int(input())
for i in range(q):
	n = int(input())
	a = [int(i) for i in input().split()]
	A = set()
	numbers = {}
	for i in a:
		if i not in A:
			numbers[i] = 1
			A.add(i)
		else:
			numbers[i] += 1
	new = []
	for i in A:
		new.append(numbers[i])
	new.sort(key=lambda x: -x)
	now = new[0]
	s = new[0]
	for i in range(1, len(new)):
		if now == 0:
			break
		if new[i] >= now:
			now = now - 1
			s += now
		else:
			now = new[i]
			s += new[i]
	print(s)


for i in range(int(input())):
	mmm = {}
	n = int(input())
	for a in map(int, input().split()):
		if a not in mmm:
			mmm[a] = 1
		else:
			mmm[a] += 1
	s = 0
	items = sorted(mmm.items(), key=lambda x: -x[1])
	_max = 99999999999999999999999
	for i in items:
		if _max == 1:
			break
		_max = min(i[1], _max - 1)
		s += _max
	print(s)


from collections import defaultdict
q = int(input())
for i in range(q):
	n = int(input())
	l = list(map(int, input().split()))
	hash = defaultdict(int)
	for i in l:
		hash[i] += 1
	la = []
	for i in hash.keys():
		la.append(hash[i])
	la.sort(reverse=True)
	ans = [la[0]]
	prev = la[0]
	for i in la[1:]:
		z = ans[-1]
		if i >= z:
			if z - 1 > 0:
				ans.append(z - 1)
		else:
			ans.append(i)
	print(sum(ans))


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

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

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

def f(n):
	s = str(n)
	c = 0
	for i in s:
		c += int(i)
	if c % 4 == 0:
		return 1
	else:
		return 0
t = ii()
while t:
	t -= 1
	n = ii()
	m = {}
	a = li()
	for i in range(n):
		if a[i] not in m:
			m[a[i]] = 1
		else:
			m[a[i]] += 1
	s = []
	for i in m.values():
		s.append(i)
	del m
	m = {}
	for i in s:
		if i not in m:
			m[i] = 1
		else:
			m[i] += 1
	b = []
	c = []
	for i in s:
		if m[i] == 1:
			b.append(i)
		else:
			c.append(i)
	c.sort()
	m = 1
	for i in c:
		for j in range(i, 0, -1):
			if j not in b:
				b.append(j)
				break
	print(sum(b))


import sys
inf = float('inf')
abc = 'abcdefghijklmnopqrstuvwxyz'
abd = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
(mod, MOD) = (1000000007, 998244353)
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

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

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

def input():
	return sys.stdin.readline().strip()
q = int(input())
while q > 0:
	n = int(input())
	Arr = get_array()
	mydict = dict()
	for i in Arr:
		mydict[i] = mydict.get(i, 0) + 1
	myset = set()
	count = 0
	for i in mydict:
		if mydict[i] not in myset:
			count += mydict[i]
			myset.add(mydict[i])
		else:
			z = mydict[i]
			for i in range(z, 0, -1):
				if i not in myset:
					count += i
					myset.add(i)
					break
	print(count)
	q -= 1


from collections import Counter
query_num = int(input())
ans = []
for j in range(query_num):
	num = input()
	arr = list(input().split())
	num_count_dict = Counter(arr)
	candy_size = 0
	num_count_list = sorted(num_count_dict.values(), reverse=True)
	curr_max = int(1000000000.0)
	for val in num_count_list:
		curr_max = max(min(val, curr_max - 1), 0)
		candy_size += curr_max
	ans.append(candy_size)
for val in ans:
	print(val)


from collections import Counter
q = int(input())
prints = []
for i in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	b = Counter(a)
	listA = list(b.values())
	listA.sort()
	listA.reverse()
	total = 0
	for i in range(1, len(listA)):
		if listA[i] >= listA[i - 1]:
			listA[i] = listA[i - 1] - 1
	x = 0
	for i in listA:
		if i > 0:
			x += i
	prints.append(str(x))
print('\n'.join(prints))


t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	count = 1
	truth = [False for j in range(n + 1)]
	fill = 0
	total = 0
	for j in range(1, n):
		if truth[count] == False:
			fill = count
		if l[j] == l[j - 1]:
			count += 1
		else:
			if truth[fill] == False:
				truth[fill] = True
				total += fill
			fill = 0
			count = 1
	if truth[count] == False:
		fill = count
	if truth[fill] == False:
		truth[fill] = True
		total += fill
	print(total)


from collections import defaultdict
for _ in range(int(input())):
	input()
	d = defaultdict(int)
	for x in input().split():
		d[int(x)] += 1
	a = sorted([x for x in d.values()], reverse=True)
	r = a[0]
	itera = enumerate(a)
	next(itera)
	for (i, v) in itera:
		if v >= a[i - 1]:
			a[i] = a[i - 1] - 1
		if a[i] < 0:
			break
		r += a[i]
	print(r)


q = int(input())
for i in range(q):
	n = int(input())
	a = [int(x) for x in input().split()]
	dic = {}
	b = []
	counter = 0
	for item in a:
		if item not in dic:
			dic[item] = 1
		else:
			dic[item] += 1
	for item in dic:
		b.append(dic[item])
	b.sort(reverse=True)
	x = b[0] + 1
	for item in b:
		x = min(x - 1, item)
		counter += max(x, 0)
	print(counter)


from collections import defaultdict
from sys import stdin, stdout
q = int(stdin.readline())
for it in range(q):
	n = int(stdin.readline())
	d = [0] * n
	f = [0] * n
	for i in range(n):
		(t, b) = map(int, stdin.readline().split())
		d[t - 1] += 1
		if b == 1:
			f[t - 1] += 1
	d = [(x, i) for (i, x) in enumerate(d)]
	d.sort(reverse=True)
	s = set()
	ans = 0
	ans_f = 0
	cur = n
	idx = 0
	while cur > 0:
		while idx < len(d) and d[idx][0] == cur:
			d1 = d[idx]
			s.add((f[d1[1]], d1[1]))
			idx += 1
		if s:
			ans += cur
			e = max(s)
			ans_f += min(cur, e[0])
			s.remove(e)
		cur -= 1
	stdout.write(str(ans) + ' ' + str(ans_f) + '\n')


from sys import stdin
t = int(stdin.readline().rstrip())
while t > 0:
	n = int(stdin.readline().rstrip())
	l = list(map(int, stdin.readline().split()))
	d = {}
	for i in l:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	k = []
	for i in d.values():
		k.append(i)
	k.sort(reverse=True)
	p = k[0]
	s = k[0]
	q = 0
	if n == 1:
		print(s)
	else:
		for i in range(1, len(k)):
			if k[i] < p:
				s += k[i]
				p = k[i]
			else:
				s += p - 1
				p -= 1
				if p == 0:
					break
		print(s)
	t -= 1


import sys
for _ in range(int(input())):
	n = int(sys.stdin.readline())
	a = list(map(int, sys.stdin.readline().split()))
	if n == 1:
		print(1)
		continue
	if n == 2:
		if a[0] == a[1]:
			print(2)
		else:
			print(1)
		continue
	d = {}
	for i in a:
		if i not in d:
			d[i] = 0
		d[i] += 1
	vals = list(d.values())
	vals.sort(reverse=True)
	s = 0
	l = max(vals) + 1
	for i in vals:
		if i < l:
			s += i
			l = i
		elif l - 1 > 0:
			s += l - 1
			l = l - 1
		else:
			break
	print(s)


from sys import stdin
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	ar = list(map(int, stdin.readline().split()))
	d = [0 for _ in range(n + 1)]
	for i in ar:
		d[i] += 1
	d.sort(reverse=True)
	ans = 0
	cur = d[0] + 1
	for i in d:
		if i < cur:
			cur = i
		else:
			cur -= 1
		ans += cur
		if cur == 1 or i == 0:
			break
	print(ans)


from collections import defaultdict
from math import sqrt

def go():
	n = int(input())
	s = 0
	d = defaultdict(int)
	for item in input().split(' '):
		d[int(item)] += 1
	used = [False] * (n + 1)
	for key in d:
		value = d[key]
		while used[value] and value > 0:
			value -= 1
		s += value
		used[value] = True
	return s
o = ''
Q = int(input())
for _ in range(Q):
	o += str(go()) + '\n'
print(o)


from collections import Counter
R = lambda : map(int, input().rstrip().split())
for _ in range(int(input())):
	n = int(input())
	c = Counter(R())
	li = list(c.values())
	li.sort(reverse=True)
	ans = li[0]
	t = li[0] - 1
	m = len(li)
	i = 1
	while t > 0 and i < m:
		x = min(t, li[i])
		ans += x
		t = x - 1
		i += 1
	print(ans)


from sys import stdin
input = stdin.readline
q = int(input())
for query in range(q):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	roz = 1
	for i in range(1, n):
		if l[i - 1] != l[i]:
			roz += 1
	d = l + [-1]
	ziom = [0] * roz
	count = 1
	j = 0
	for i in range(1, n + 1):
		if d[i] == d[i - 1]:
			count += 1
		else:
			ziom[j] = count
			j += 1
			count = 1
	ziom.sort()
	thres = 1000000000000000000000
	wyn = 0
	i = len(ziom) - 1
	while True:
		if thres <= 0 or i < 0:
			print(wyn)
			break
		wyn += min(thres - 1, ziom[i])
		thres = min(thres - 1, ziom[i])
		i -= 1


import os
import sys
from io import BytesIO, IOBase
import math
from itertools import permutations
from decimal import Decimal, getcontext
getcontext().prec = 25
MOD = pow(10, 9) + 7
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split(' ')))
	d = {}
	for i in range(n):
		d[l[i]] = d.get(l[i], 0) + 1
	x = list(d.values())
	x.sort(reverse=True)
	c = x[0]
	ans = c
	c -= 1
	for i in range(1, len(x)):
		if x[i] >= c:
			ans += c
			c = max(c - 1, 0)
		else:
			ans += x[i]
			c = x[i] - 1
	print(ans)


t = int(input())
for q in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	d = {}
	for i in range(n):
		if a[i] in d:
			d[a[i]] += 1
		else:
			d[a[i]] = 1
	l = list(d.values())
	l.sort(reverse=True)
	ans = l[0]
	x = l[0]
	for i in range(1, len(l)):
		if x > 0:
			x = min(x - 1, l[i])
			ans += x
	print(ans)


q = int(input())
for _ in range(q):
	n = int(input())
	s = [0] * n
	for i in map(int, input().split()):
		s[i - 1] += 1
	s.sort(reverse=True)
	m = 2 * 10 ** 5
	sum = 0
	for i in s:
		m = max(min(m, i), 0)
		sum += m
		m -= 1
	print(sum)


import collections
n = int(input())
answers = [0] * n
for i in range(n):
	cnt = int(input())
	if cnt == 1:
		input()
		answers[i] = '1'
		continue
	used = set()
	c = collections.Counter(map(int, input().split())).most_common()
	ans = x = c.pop(0)[1]
	used.add(x)
	for (_, v) in c:
		while v in used:
			v -= 1
		if v <= 0:
			break
		x = v
		used.add(x)
		ans += x
	answers[i] = str(ans)
print('\n'.join(answers))


from sys import stdin, stdout

def solve():
	n = int(stdin.readline())
	x = []
	l = list(map(int, stdin.readline().split()))
	d = {}
	for i in l:
		d[i] = d.get(i, 0) + 1
	for i in d:
		x.append(d[i])
	x.sort(reverse=True)
	s = set()
	c = 0
	for i in x:
		if i not in s:
			c += i
			s.add(i)
		else:
			while i in s:
				i -= 1
			if i > 0:
				s.add(i)
				c += i
	print(c)
for _ in range(int(stdin.readline())):
	solve()


def solve():
	from sys import stdin, stdout
	for _ in range(int(stdin.readline())):
		n = int(stdin.readline())
		l = list(map(int, stdin.readline().split()))
		b = [0] * n
		for i in l:
			b[i - 1] += 1
		b.sort(reverse=True)
		c = 0
		for i in range(1, len(b)):
			if b[i] - b[i - 1] >= 0:
				b[i] = b[i - 1] - 1
		for i in b:
			if i > 0:
				c += i
			else:
				break
		stdout.write(str(c) + '\n')
solve()


for _ in range(int(input())):
	n = int(input())
	s = [0] * (n + 1)
	a = list(map(int, input().split()))
	x = 0
	for i in range(n):
		s[a[i]] += 1
		if s[a[i]] > x:
			x = s[a[i]]
	z = [0] * (x + 1)
	p = 0
	for i in range(1, n + 1):
		x = s[i]
		if not z[x]:
			p += x
			z[x] = 1
		else:
			while x:
				if not z[x]:
					p += x
					z[x] = 1
					break
				x -= 1
	print(p)


t = int(input())
for v in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	if n == 1:
		print(arr[0])
		continue
	l = [0] * n
	for i in range(n):
		l[arr[i] - 1] += 1
	l.sort()
	s = 0
	i = n - 1
	pr = l[n - 1]
	while i >= 0 and pr > 0:
		pr = min(pr, l[i])
		s += pr
		pr -= 1
		i -= 1
	print(s)


from sys import *
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	b = [0] * max(a)
	for i in a:
		b[i - 1] += 1
	b.sort()
	b = b[::-1]
	m = b[0]
	cnt = b[0]
	for i in range(1, len(b)):
		if b[i] >= m:
			b[i] = b[i - 1] - 1
			b[i] = max(0, b[i])
		m = b[i]
		cnt += b[i]
	print(cnt)


import sys
input = sys.stdin.readline
for q in range(int(input())):
	n = int(input())
	num = list(map(int, input().split()))
	cal = []
	p = (n + 1) * [0]
	for i in range(n):
		p[num[i]] += 1
	for j in range(n + 1):
		cal.append(p[j])
	cal.sort()
	l = len(cal)
	x = cal[l - 1]
	ans = 0
	for i in range(l):
		ans += x
		if i == l - 1:
			break
		x = max(0, min(x - 1, cal[l - i - 2]))
	print(ans)


from collections import defaultdict
import sys
import heapq

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

def solution():
	n = int(input())
	candi = [[0, 0] for i in range(n + 1)]
	que = []
	for i in range(n):
		(taste, youwant) = map(int, input().split())
		if youwant == 1:
			candi[taste][0] += 1
		else:
			candi[taste][1] += 1
	for i in range(n + 1):
		s = sum(candi[i])
		if s > 0:
			que.append((-s, -candi[i][0], -candi[i][1]))
	heapq.heapify(que)
	ans = 0
	badcnt = 0
	border = -que[0][0]
	stocked = []
	heapq.heapify(stocked)
	ording = 0
	while (que or stocked) and border > 0:
		ording += 1
		while que and que[0][0] <= -border:
			(poped_cnt, poped_good_candi, poped_bad_candi) = heapq.heappop(que)
			heapq.heappush(stocked, (poped_good_candi, poped_bad_candi))
		if not stocked:
			if que:
				border = -que[0][0]
			continue
		if stocked:
			(good_candi, bad_candi) = heapq.heappop(stocked)
			good_candi *= -1
			bad_candi *= -1
			sums = good_candi + bad_candi
			if sums < border:
				ans += sums
				border = sums - 1
				badcnt += good_candi
				continue
			elif sums >= border:
				ans += border
				badcnt += min(border, good_candi)
				border -= 1
				continue
	print(ans, badcnt)
	return

def main():
	test = int(input())
	for i in range(test):
		solution()
	return
main()


import sys
import os
from io import IOBase, BytesIO

def main():
	from collections import Counter
	from operator import itemgetter
	for tc in range(int(input())):
		n = int(input())
		arr = get_array()
		d = Counter(arr)
		d = sorted(d.items(), key=itemgetter(1), reverse=True)
		x = {}
		ans = 0
		lb = float('inf')
		for (k, v) in d:
			if lb == 0:
				break
			if v < lb:
				ans += v
				lb = v
			else:
				ans += lb - 1
				lb -= 1
		print(ans)
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

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

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		py2 = round(0.5)
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2 == 1:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			self.write = lambda s: self.buffer.write(s.encode('ascii'))
			self.read = lambda : self.buffer.read().decode('ascii')
			self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

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

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

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


from collections import Counter
import sys
input = sys.stdin.readline
for _ in range(int(input())):
	N = int(input())
	List = [int(x) for x in input().split()]
	Dict = Counter(List)
	X = list(Dict.values())
	X.sort()
	Ans = X[-1]
	curr = X[-1] - 1
	for i in range(len(X) - 2, -1, -1):
		if curr == 0:
			break
		if X[i] >= curr:
			Ans += curr
			curr -= 1
		else:
			Ans += X[i]
			curr = X[i] - 1
	print(Ans)


for i in range(int(input())):
	n = int(input())
	x = list(map(int, input().split()))
	a = n * [0]
	for j in range(n):
		a[x[j] - 1] += 1
	a.sort(reverse=True)
	z = a[0] - 1
	ans = a[0]
	for k in range(1, n):
		if a[k] <= z:
			z = a[k]
		ans += z
		z -= 1
		if z < 0:
			break
	print(ans)


import sys
input = sys.stdin.readline
from math import *
t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	a = [int(x) for x in input().split()]
	d = [0 for i in range(n + 1)]
	for i in a:
		d[i] += 1
	d.sort(reverse=True)
	k = max(d)
	c = 0
	for i in range(len(d)):
		c += min(k, d[i])
		k = min(k, d[i]) - 1
		if k <= 0:
			break
	print(c)


q = int(input())
res = []
for x in range(q):
	n = int(input())
	a = {}
	for i in input().split():
		i = int(i)
		if i in a:
			a[i] += 1
		else:
			a[i] = 1
	M = n + 1
	r = 0
	while M != 0 and a != {}:
		maxId = max(a, key=a.get)
		if a[maxId] >= M:
			M -= 1
		else:
			M = a[maxId]
		a.pop(maxId)
		r += M
	res.append(r)
for i in res:
	print(i)


for _ in range(int(input())):
	n = int(input())
	lis = list(map(int, input().split()))
	x = {}
	for i in lis:
		if i not in x:
			x[i] = 1
		else:
			x[i] += 1
	res = list(x.values())
	visited = []
	res = sorted(res, reverse=True)
	ans = 0
	for i in res:
		while i in visited and i > 0:
			i -= 1
		visited.append(i)
		ans += i
	print(ans)


for _ in range(int(input())):
	a = int(input())
	c = [int(x) for x in input().split()]
	n = [0] * (a + 1)
	for j in c:
		n[j] += 1
	n.sort(reverse=True)
	s = n[0]
	p = n[0]
	for j in range(1, a + 1):
		if p == 1:
			break
		if n[j] == 0:
			break
		if n[j] >= p:
			s += p - 1
			p = p - 1
			if p == 1:
				break
		elif n[j] < p:
			s += n[j]
			p = n[j]
			if p == 1:
				break
	print(s)


import sys
input = sys.stdin.readline
from collections import Counter
q = int(input())
for _ in range(q):
	n = int(input())
	a = [int(i) for i in input().split()]
	c = Counter(a)
	num = [i[1] for i in c.items()]
	num.sort()
	ma = num.pop()
	ans = ma
	for x in num[::-1]:
		if x >= ma:
			ans += ma - 1
			ma -= 1
		else:
			ma = x
			ans += ma
		if ma == 0:
			break
	print(ans)


def make(list):
	dic = {}
	n = len(list)
	for i in range(n):
		if list[i] in dic:
			dic[list[i]] += 1
		else:
			dic[list[i]] = 1
	l = []
	for i in dic:
		l.append(dic[i])
	l.sort()
	s = 0
	prev = n + 1
	for i in range(len(l) - 1, -1, -1):
		if l[i] < prev:
			s += l[i]
			prev = l[i]
		elif prev - 1 >= 0:
			s += prev - 1
			prev = prev - 1
	return s
n = int(input())
for i in range(n):
	m = int(input())
	l = list(map(int, input().strip().split()))
	print(make(l))


q = int(input())
for x in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	tab = [0] * (max(a) + 1)
	for item in a:
		tab[item] += 1
	tab.sort()
	i = len(tab) - 1
	o = tab[-1]
	s = 0
	while i >= 0 and o > 0:
		k = min(o, tab[i])
		o = k - 1
		s += k
		i -= 1
	print(s)


for _ in range(int(input())):
	n = int(input())
	b = [0] * n
	for i in map(int, input().split()):
		b[i - 1] += 1
	b.sort(reverse=True)
	init = b[0]
	cnt = init
	for i in range(1, len(b)):
		if b[i] >= init:
			init -= 1
			if init <= 0:
				break
			cnt += init
		else:
			init = b[i]
			cnt += init
		if init <= 0:
			break
	print(cnt)


q = int(input())
L = lambda : list(map(int, input().split()))
for quer in range(q):
	n = int(input())
	a = L()
	c = [0] * (n + 1)
	d = [0] * (n + 1)
	for i in a:
		c[i] += 1
	for i in c:
		d[i] += 1
	mx = n + 1
	ans = 0
	for i in range(n, 0, -1):
		if d[i] > 0:
			if i < mx:
				ans += i
				mx = i
			else:
				ans += mx - 1
				mx -= 1
			d[i - 1] += d[i] - 1
	print(ans)


from collections import defaultdict
q = int(input())
ans = []
for _ in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	count = defaultdict(int)
	for v in a:
		count[v] += 1
	sum_ = 0
	pre_v = 10 ** 6
	for v in sorted(count.values(), reverse=True):
		if pre_v == 0:
			break
		if pre_v <= v:
			v = pre_v - 1
		sum_ += v
		pre_v = v
	ans.append(str(sum_))
print('\n'.join(ans))


for ii in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	cnt = {}
	for i in a:
		if i not in cnt.keys():
			cnt[i] = 1
		else:
			cnt[i] += 1
	l = sorted([i for i in cnt.values()])
	min_last = l[-1] + 1
	ans = 0
	for i in reversed(range(len(l))):
		min_last = max(min(l[i], min_last - 1), 0)
		ans += min_last
	print(ans)


def get_number(A):
	B = {}
	for i in A:
		B[i] = B.get(i, 0) + 1
	return sorted(list(B.values()), reverse=True)

def Candy_Box(A):
	B = get_number(A)
	D = [B[0]]
	for i in range(1, len(B)):
		if D[i - 1] > 0:
			D.append(min(D[i - 1] - 1, B[i]))
		else:
			break
	return sum(D)
q = int(input())
C = []
for i in range(q):
	n = int(input())
	A = []
	for x in input().split():
		A.append(int(x))
	C.append(Candy_Box(A))
for i in C:
	print(i)


for _ in range(int(input())):
	a = int(input())
	b = list(map(int, input().split()))
	c = [0] * (a + 1)
	d = [0] * (a + 1)
	for i in b:
		c[i] += 1
	c.sort(reverse=True)
	for i in c:
		d[i] += 1
	k = 0
	l = 0
	for j in range(a, 0, -1):
		if d[j] > 0:
			k += j
			l += d[j] - 1
		elif l > 0:
			k += j
			l -= 1
	print(k)


SS = []
a = int(input())
for i in range(a):
	x = int(input())
	A = list(map(int, input().split()))
	D = {}
	for j in range(x):
		if A[j] in D:
			D[A[j]] += 1
		else:
			D[A[j]] = 1
	B = []
	for key in D:
		B.append(D[key])
	B.sort(reverse=True)
	w = B[0]
	for j in range(1, len(B)):
		if B[j] < B[j - 1] - 1:
			w += max(0, B[j])
		else:
			B[j] = B[j - 1] - 1
			w += max(0, B[j - 1] - 1)
	SS.append(w)
for s in SS:
	print(s)


N = int(input())
answer = []
for i in range(N):
	n = int(input())
	a = list(map(int, input().split()))
	dict_a = {}
	for x in a:
		if x in dict_a:
			dict_a[x] += 1
		else:
			dict_a[x] = 1
	s = set()
	for value in dict_a.values():
		while value > 0:
			if value in s:
				value -= 1
			else:
				s.add(value)
				break
	answer.append(sum(s))
for x in answer:
	print(x)


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	m = {}
	for x in a:
		if x in m:
			m[x] += 1
		else:
			m[x] = 1
	lst = list(m.values())
	lst.sort(reverse=True)
	m = {}
	for x in lst:
		if x in m:
			m[x] += 1
		else:
			m[x] = 1
	val = 0
	res = set()
	for x in m:
		left = x
		right = m[x]
		tmp = left
		while right > 0:
			while tmp > 0:
				if tmp not in res:
					val += tmp
					res.add(tmp)
					break
				tmp -= 1
			right -= 1
	print(val)


def readInts():
	return [int(x) for x in input().split()]
Q = int(input())
results = []
for q in range(Q):
	N = int(input())
	A = readInts()
	freqs = {}
	for a in A:
		freqs[a] = freqs.get(a, 0) + 1
	counts = list(freqs.values())
	counts.sort(reverse=True)
	result = 0
	ceil = counts[0]
	for c in counts:
		result += min(ceil, c)
		ceil = min(ceil, c) - 1
		if ceil == 0:
			break
	results.append(result)
print(*results, sep='\n')


q = int(input())
for i in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	d = {}
	for i in a:
		d[i] = d.get(i, 0) + 1
	s = list(d.values())
	s.sort(reverse=True)
	tc = s[0]
	ans = tc
	for i in range(1, len(s)):
		if s[i] >= tc - 1:
			tc -= 1
		else:
			tc = s[i]
		if tc > 0:
			ans += tc
	print(ans)


from sys import stdin
q = int(stdin.readline().strip())
for _ in range(q):
	n = int(stdin.readline().strip())
	a = [int(i) for i in stdin.readline().strip().split()]
	d = {}
	for i in a:
		d[i] = d.get(i, 0) + 1
	counts = sorted(d.values(), reverse=True)
	got = set()
	max_ = counts[0]
	min_ = counts[0]
	res = 0
	for c in counts:
		if c not in got:
			got.add(c)
			res += c
			min_ = min(min_, c)
		elif min_ > 0:
			res += min_ - 1
			got.add(min_ - 1)
			min_ -= 1
	print(res)


for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	di = {}
	for i in a:
		if i not in di:
			di[i] = 1
		else:
			di[i] = di[i] + 1
	count = list(di.values())
	count.sort(reverse=True)
	ans = 0
	lc = len(count)
	prev = count[0] + 1
	for i in range(lc):
		if prev <= count[i]:
			prev = prev - 1
			ans = ans + prev
		else:
			ans = ans + count[i]
			prev = count[i]
		if prev == 0:
			break
	print(ans)


t = int(input())
for i in range(1, t + 1):
	n = int(input())
	box = list(map(int, input().split()))
	d = {}
	for candy in box:
		if candy in d:
			d[candy] += 1
		else:
			d[candy] = 1
	s = sorted(d.items(), key=lambda k: k[1], reverse=True)
	taken = []
	sum = 0
	pick = 1
	flag = 0
	for it in s:
		if it[1] not in taken:
			sum += it[1]
			taken.append(it[1])
		else:
			pick = it[1] - 1
			while pick > 0:
				if pick not in taken:
					sum += pick
					taken.append(pick)
					break
				else:
					pick -= 1
	print(sum)


import sys, os
from io import BytesIO, IOBase
import collections, itertools, bisect, heapq, math, string
BUFSIZE = 8192
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():
	q = int(input())
	for i in range(q):
		n = int(input())
		a = list(map(int, input().split()))
		d = collections.Counter(a)
		sd = sorted(d.items(), key=lambda x: x[1], reverse=True)
		s = set()
		mn = len(a)
		for x in sd:
			mn = min(mn, x[1])
			if mn not in s and mn != 0:
				s.add(mn)
				mn = mn - 1
		print(sum(s))
main()


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

def candyBox(ans):
	for i in range(0, len(ans)):
		if ans[i] != 0:
			for j in range(i + 1, len(ans)):
				if ans[i] == ans[j] and ans[i] != 0:
					ans[j] -= 1
	return sum(ans)
for _ in range(0, int(input())):
	input()
	a = [value for (key, value) in sorted(Counter(map(int, input().split())).items(), key=lambda item: item[1], reverse=True)]
	if len(set(a)) == len(a):
		print(sum(a))
	else:
		print(candyBox(a))


import sys
q = int(sys.stdin.readline())
for _ in range(q):
	n = int(sys.stdin.readline())
	a = list(map(int, sys.stdin.readline().split()))
	table = dict()
	for i in range(n):
		table[a[i]] = 0
	for i in range(n):
		table[a[i]] += 1
	table = list(table.items())
	table = sorted(table, key=lambda ele: -ele[1])
	res = 0
	table2 = dict()
	for i in range(len(table)):
		cnt = table[i][1]
		if cnt not in table2:
			res += cnt
			table2[cnt] = 1
		else:
			while cnt in table2:
				cnt -= 1
			if cnt >= 1:
				res += cnt
				table2[cnt] = 1
			else:
				break
	print(res)


from collections import Counter

def main():
	q = int(input())
	for qi in range(q):
		n = int(input())
		if n == 1:
			_ = input()
			print(1)
			continue
		ns = Counter(input().split())
		min_used = 300000.0
		res = 0
		for (_, cnt) in ns.most_common():
			if min_used == 0:
				break
			if cnt >= min_used:
				res += min_used - 1
				min_used -= 1
			else:
				res += cnt
				min_used = cnt
		print(res)
main()


q = int(input())
for i in range(q):
	n = int(input())
	konfs = {}
	for k in input().split():
		if k not in konfs:
			konfs[k] = 0
		konfs[k] += 1
	konfs = sorted(konfs.items(), key=lambda x: x[1])
	cnt = 0
	latest_count = None
	used = [0]
	for (type, count) in konfs:
		if count not in used:
			used.append(count)
			cnt += count
		else:
			latest = used[-1]
			for j in range(len(used) - 2, -1, -1):
				if used[j] != latest - 1:
					used.insert(j + 1, latest - 1)
					cnt += latest - 1
					break
				latest = used[j]
	print(cnt)


import sys
from collections import Counter
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	c = Counter(a)
	s = set()
	for i in c.values():
		if i not in s:
			s.add(i)
		else:
			j = i
			while j > 0 and j in s:
				j -= 1
			s.add(j)
	print(sum(s))


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

def main():
	from collections import Counter
	q = int(input())
	for _ in range(q):
		n = int(input())
		a = [int(x) for x in input().split()]
		count = Counter(a)
		freq = [count[x] for x in count]
		freq.sort(reverse=True)
		result = 0
		prev = float('inf')
		for val in freq:
			if val < prev:
				result += val
				prev = val
			elif prev >= 2:
				result += prev - 1
				prev -= 1
		print(result)
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()


t = int(input())
for z in range(t):
	n = int(input())
	a = []
	max = 0
	count = 0
	b = []
	a = [int(x) for x in input().split()]
	fq = [0] * (n + 1)
	for i in range(n):
		fq[a[i]] += 1
	fq.sort(reverse=True)
	f = 0
	for i in range(n + 1):
		if fq[i] == 0:
			break
		if fq[i] not in b:
			b.append(fq[i])
			count += fq[i]
		else:
			while fq[i] in b:
				fq[i] -= 1
				if fq[i] == 0:
					f = 1
					break
			if f == 1:
				break
			b.append(fq[i])
			count += fq[i]
	print(count)


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')
n = int(input())
for i in range(n):
	t = int(input())
	l = list(map(int, input().split()))
	l.sort()
	cur = 1
	s = []
	for j in range(1, t):
		if l[j] == l[j - 1]:
			cur += 1
		else:
			s.append(cur)
			cur = 1
	s.append(cur)
	s.sort(reverse=True)
	cur = s[0]
	ans = s[0]
	for i in range(1, len(s)):
		cur = min(cur - 1, s[i])
		if cur <= 0:
			break
		ans += cur
	print(ans)


from sys import stdin, stdout
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	arr = list(map(int, stdin.readline().split()))
	d = {}
	for i in arr:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	cnt = list((d[i] for i in d))
	cnt.sort(reverse=True)
	ans = []
	ans.append(cnt[0])
	for i in range(1, len(cnt)):
		if cnt[i - 1] != 0:
			while cnt[i] > 0:
				if cnt[i] not in ans:
					ans.append(cnt[i])
					break
				else:
					cnt[i] -= 1
		else:
			break
	stdout.write('{}\n'.format(sum(ans)))


from sys import stdin, stdout
input = stdin.readline
from collections import Counter
p = int(input())
for i in range(0, p):
	n = int(input())
	a = list(map(int, input().split()))
	k = Counter(a)
	k = list(k.values())
	k.sort(reverse=True)
	m = k[0]
	s = k[0]
	for j in range(1, len(k)):
		if k[j] >= m:
			s = s + m - 1
			m -= 1
		elif k[j] < m:
			s = s + k[j]
			m = k[j]
		if m <= 0:
			break
	print(s)


q = int(input())
for _ in range(q):
	n = int(input())
	d = {}
	for x in input().split():
		d[int(x)] = d.get(int(x), 0) + 1
	mini = 200006
	ans = 0
	for x in sorted(d.values(), reverse=True):
		if mini == 0:
			break
		t = min(mini, x)
		ans += t
		mini = t - 1
	print(ans)


for q in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l.sort()
	summ = 0
	i = 0
	count = 0
	c = []
	prev = l[0]
	while i < len(l):
		if prev == l[i]:
			count += 1
		else:
			c.append(count)
			count = 1
			prev = l[i]
		i += 1
	c.append(count)
	cn = sorted(c, reverse=True)
	i = 0
	maxx = cn[0]
	while i < len(cn) and maxx > 0:
		if maxx > cn[i]:
			maxx -= 1
		else:
			summ += maxx
			maxx -= 1
			i += 1
	print(summ)


for i in range(int(input())):
	n = int(input())
	line = list(map(int, input().split()))
	d = {}
	for i in line:
		d[i] = d.get(i, 0) + 1
	values = sorted(d.values(), reverse=True)
	m = values[0] - 1
	size = values[0]
	for i in range(1, len(values)):
		if m <= 0:
			break
		if values[i] > m:
			size += m
			m -= 1
		else:
			m = values[i] - 1
			size += m + 1
	print(size)


import sys
input = sys.stdin.readline
q = int(input())
for _ in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	memo = {}
	for num in a:
		if num not in memo:
			memo[num] = 1
		else:
			memo[num] += 1
	tmp = [0] * len(memo)
	for (i, num) in enumerate(memo):
		tmp[i] = memo[num]
	tmp = sorted(tmp, reverse=True)
	ans = 0
	max_num = 10 ** 9 + 7
	for num in tmp:
		if max_num <= num:
			max_num = max(0, max_num - 1)
			ans += max_num
		else:
			ans += num
			max_num = num
	print(ans)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l1 = []
	cnt = 0
	l.sort()
	for i in range(n - 1):
		cnt += 1
		if l[i] != l[i + 1]:
			l1.append(cnt)
			cnt = 0
	l1.append(l.count(l[n - 1]))
	l1.sort()
	l1.reverse()
	cnt = l1[0]
	sum = l1[0]
	for i in range(1, len(l1)):
		cnt1 = l1[i]
		if cnt == 0:
			break
		if cnt <= cnt1:
			cnt -= 1
		else:
			cnt = cnt1
		sum += cnt
	print(sum)


q = int(input())
while q > 0:
	q = q - 1
	n = int(input())
	a = list(map(int, input().split()))
	a.sort(reverse=True)
	c = [1]
	l = 0
	curVal = a[0]
	i = 1
	while i < n:
		if a[i] == curVal:
			c[l] = c[l] + 1
		else:
			c.append(1)
			l = l + 1
			curVal = a[i]
		i = i + 1
	c.sort(reverse=True)
	l = l + 1
	i = 1
	r = c[0]
	while i < l:
		if c[i] >= c[i - 1]:
			c[i] = c[i - 1] - 1
		if c[i] > 0:
			r = r + c[i]
		else:
			break
		i = i + 1
	print(r)


import sys
import math

def getAndParseInt(num=1):
	string = sys.stdin.readline().strip()
	if num == 1:
		return int(string)
	else:
		return [int(part) for part in string.split()]

def getAndParseString(num=1, delim=' '):
	string = sys.stdin.readline().strip()
	if num == 1:
		return string
	else:
		return [part for part in string.split(delim)]
q = getAndParseInt()
for i in range(q):
	n = getAndParseInt()
	candies = getAndParseInt(2)
	hashTable = {}
	for candy in candies:
		cnt = hashTable.get(candy, 0)
		hashTable[candy] = cnt + 1
	counts = {}
	for (key, val) in hashTable.items():
		cnt = counts.get(val, 0)
		counts[val] = cnt + 1
	countListSorted = sorted(list(counts.keys()), reverse=True)
	maxPossible = 0
	curUpper = countListSorted[0]
	for num in countListSorted:
		if curUpper > num:
			curUpper = num
		curCnt = counts[num]
		while curUpper >= 1 and curCnt > 0:
			maxPossible += curUpper
			curUpper -= 1
			curCnt -= 1
	print(maxPossible)


from collections import Counter
from sys import stdin
input = stdin.buffer.readline

def dif_sums(a, b):
	return a * (a + 1) // 2 - b * (b - 1) // 2
q = int(input())
for _ in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	a.sort()
	c = Counter(a)
	if n == 1:
		print(1)
	else:
		vs = []
		for (k, v) in c.items():
			vs.append(v)
		vs = sorted(vs)[::-1]
		l = vs[0]
		s = l
		for i in range(1, len(vs)):
			if vs[i] >= l:
				l -= 1
			else:
				l = vs[i]
			s += max(0, l)
		print(s)


import sys
input = sys.stdin.buffer.readline
import heapq

def main():
	q = int(input())
	for _ in range(q):
		n = int(input())
		A = list(map(int, input().split()))
		d = {}
		for a in A:
			if a not in d:
				d[a] = 1
			else:
				d[a] += 1
		V = list(d.values())
		V.sort(reverse=True)
		used = set()
		ans = 0
		for v in V:
			if v not in used:
				ans += v
				used.add(v)
			else:
				flag = False
				while v in used:
					v -= 1
					if v == 0:
						flag = True
						break
				if flag:
					break
				else:
					ans += v
					used.add(v)
		print(ans)
main()


from collections import Counter
for _ in range(int(input())):
	(siz, cj, ans) = (input(), 0, 0)
	ct = Counter(map(int, input().split()))
	for m in ct.most_common():
		if not cj:
			cj = m[1]
			ans += cj
		elif cj:
			if cj <= m[1]:
				cj -= 1
				ans += cj
				if not cj:
					break
			else:
				cj = m[1]
				ans += cj
	print(ans)


import sys
input = sys.stdin.readline
from collections import Counter
Q = int(input())
for testcase in range(Q):
	n = int(input())
	A = Counter(list(map(int, input().split())))
	S = sorted(list(A.values()), reverse=True)
	NOW = 10 ** 10
	ANS = 0
	for s in S:
		M = min(NOW, s)
		ANS += M
		NOW = M - 1
		if NOW == 0:
			break
	print(ANS)


for _ in range(int(input())):
	n = int(input())
	c = [0] * n
	for i in map(int, input().split()):
		c[i - 1] += 1
	c.sort(reverse=True)
	res = c[0]
	last = c[0]
	for x in c[1:]:
		if last == 0:
			break
		if x >= last:
			last -= 1
		else:
			last = x
		res += last
	print(res)


from sys import *
q = int(stdin.readline())
while q:
	q = q - 1
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	Hash = [0] * (n + 1)
	for i in a:
		Hash[i] += 1
	Hash.sort(reverse=True)
	res = 0
	now = int(1000000000.0)
	for i in Hash:
		now = max(min(now - 1, i), 0)
		res += now
	stdout.write(str(res) + '\n')


t = int(input())
while t:
	n = int(input())
	a = list(map(int, input().split()))
	b = (n + 1) * [0]
	for i in a:
		b[i] += 1
	b.sort(reverse=True)
	ans = b[0]
	x = b[0] - 1
	for i in range(1, n + 1):
		if b[i] == 0 or x == 0:
			break
		if b[i] >= x:
			ans += x
			x -= 1
		elif b[i] < b[i - 1]:
			ans += b[i]
			x = b[i] - 1
	print(ans)
	t -= 1


t = int(input())
for _ in range(t):
	n = int(input())
	l = [int(x) for x in input().split()]
	d = {}
	for i in l:
		if d.get(i) == None:
			d[i] = 1
		else:
			d[i] += 1
	dict = {}
	for key in d:
		if dict.get(d[key]) == None:
			dict[d[key]] = 1
		else:
			dict[d[key]] += 1
	d = {}
	ct = 0
	for key in sorted(dict):
		i = dict[key]
		j = key
		while j > 0 and i > 0:
			if d.get(j) == None:
				d[j] = 1
				ct += j
				j -= 1
				i -= 1
			else:
				j -= 1
	print(ct)


import sys
for _ in range(int(input())):
	n = int(sys.stdin.readline())
	a = list(map(int, sys.stdin.readline().split()))
	d = {}
	for i in range(n):
		if a[i] in d:
			d[a[i]] += 1
		else:
			d[a[i]] = 1
	b = list(dict.values(d))
	c = [0] * n
	ans = 0
	if b[0] == n:
		print(n)
	else:
		for i in range(len(b) - 1, -1, -1):
			if c[b[i]] == 0:
				ans += b[i]
				c[b[i]] = 1
			else:
				while c[b[i]] == 1:
					b[i] -= 1
				c[b[i]] = 1
				c[0] = 0
				ans += b[i]
		print(ans)


import sys
from functools import lru_cache
from heapq import merge, heapify, heappop, heappush
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf
from collections import defaultdict as dd, deque, Counter as c
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
mod = pow(10, 9) + 7
mod2 = 998244353

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

def out(var):
	sys.stdout.write(str(var))

def outln(var):
	sys.stdout.write(str(var) + '\n')

def l():
	return list(sp())

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

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

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

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

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
for _ in range(int(data())):
	n = int(data())
	arr = l()
	count = c(arr)
	mat = sorted(count.items(), key=lambda x: x[1])
	mat = mat[::-1]
	ans = mat[0][1]
	temp = ans
	for i in range(1, len(mat)):
		if mat[i][1] >= temp:
			ans += max(0, temp - 1)
			temp -= 1
		else:
			ans += mat[i][1]
			temp = mat[i][1]
	outln(ans)


for i in ' ' * int(input()):
	d = {}
	input()
	(*a,) = map(int, input().split())
	for i in a:
		d[i] = d.get(i, 0) + 1
	s = 0
	for i in sorted(list(d.values()), reverse=True):
		if s == 0:
			b = i
		s += min(i, b)
		b = min(i, b) - 1
		if b < 0:
			b = 0
	print(s)


from collections import defaultdict
from sys import stdin

def solve():
	results = []
	for _ in range(int(stdin.readline())):
		N = int(stdin.readline())
		A = [int(k) for k in stdin.readline().split()]
		freq = defaultdict(int)
		for x in A:
			freq[x] += 1
		s_freq = sorted(freq.items(), key=lambda k: k[1])
		cnt = s_freq[-1][1]
		last = s_freq[-1][1] - 1
		for (k, v) in reversed(s_freq[:-1]):
			if last == 0:
				break
			if v >= last:
				cnt += last
				last -= 1
			else:
				cnt += v
				last = v - 1
		results.append(cnt)
	print('\n'.join(map(str, results)))
solve()


import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
import time
from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string
start_time = time.time()

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())

def getMat(n):
	return [getInts() for _ in range(n)]

def get_ints():
	return map(int, sys.stdin.readline().split())
T = int(input())
for _ in range(T):
	n = int(input())
	ar = list(get_ints())
	d = {}
	for i in ar:
		d[i] = d.get(i, 0) + 1
	a = sorted(d.items(), key=lambda x: x[1])[::-1]
	ans = 0
	maxx = 10 ** 18
	for i in a:
		if maxx == 0:
			break
		else:
			ans += min(maxx, i[1])
			maxx = min(maxx, i[1]) - 1
	print(ans)


import sys
import operator
input = sys.stdin.readline
q = int(input())
for i in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	d = dict()
	for x in a:
		if x in d:
			d[x] += 1
		else:
			d[x] = 1
	v = []
	for k in d.items():
		_ = k[1]
		while _ in v and _ > 0:
			_ -= 1
			continue
		v.append(_)
	print(sum(v))


q = int(input())
for i in range(q):
	n = int(input())
	list = []
	for i in range(n + 1):
		list.append(0)
	out = []
	out = [int(x) for x in input().split()]
	for i in range(n):
		list[out[i]] += 1
	list.sort(reverse=True)
	ans = list[0]
	lst = list[0]
	for i in range(1, n + 1):
		if lst == 0:
			break
		if list[i] >= lst:
			ans += lst - 1
			lst = lst - 1
		else:
			ans += list[i]
			lst = list[i]
	print(ans)


from collections import defaultdict
q = int(input())
for _ in range(q):
	n = int(input())
	candies = list(map(int, input().split()))
	count = defaultdict(int)
	for i in candies:
		count[i] += 1
	vals = []
	for i in count.keys():
		vals.append(count[i])
	vals.sort(reverse=True)
	curr = vals[0]
	ans = 0
	for i in vals:
		if curr <= 0:
			break
		else:
			if i < curr:
				curr = i
			ans += curr
			curr -= 1
	print(ans)


q = int(input())
for i in range(q):
	n = int(input())
	a = [int(x) for x in input().split()]
	a.sort()
	sizes = set()
	index = 0
	while index < n:
		counter = 0
		temp = a[index]
		while index + counter < n and a[index + counter] == temp:
			counter += 1
		index += counter
		while counter > 0 and counter in sizes:
			counter -= 1
		sizes.add(counter)
	ans = 0
	for j in sizes:
		ans += j
	print(ans)


z = int(input())
for zz in range(z):
	n = int(input())
	a = list(map(int, input().split()))
	temp = [0] * (n + 1)
	for i in range(n):
		temp[a[i]] += 1
	temp.sort(reverse=True)
	last = temp[0] + 1
	res = 0
	for i in temp:
		last = max(min(last - 1, i), 0)
		res += last
	print(res)


from sys import stdin
from collections import Counter
q = int(input())
lines = stdin.readlines()
ans = []
for i in range(q):
	n = int(lines[i * 2])
	aa = map(int, lines[i * 2 + 1].split())
	cnt = list(Counter(aa).values())
	cnt.sort(reverse=True)
	x = 10 ** 19
	s = 0
	for c in cnt:
		x = max(0, min(x - 1, c))
		s += x
	ans.append(str(s))
print('\n'.join(ans))


t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	count = {}
	for num in arr:
		if num not in count:
			count[num] = 1
		else:
			count[num] += 1
	ans = sorted(count.values())[::-1]
	current = ans[0]
	final = ans[0]
	for i in range(1, len(ans)):
		if ans[i] >= current:
			current -= 1
		else:
			current = ans[i]
		final += current
		if current == 0:
			break
	print(final)


def main():
	for _ in range(int(input())):
		n = int(input())
		a = [int(i) for i in input().split()]
		d = {}
		for i in range(n):
			if a[i] not in d:
				d[a[i]] = 0
			d[a[i]] += 1
		arr = sorted(d.items(), key=lambda kv: kv[1], reverse=True)
		last = arr[0][1]
		r = arr[0][1]
		for i in range(1, len(arr)):
			if arr[i - 1][1] == arr[i][1]:
				last = max(last - 1, 0)
				r += last
			elif arr[i][1] < last:
				last = arr[i][1]
				r += last
			else:
				last = max(last - 1, 0)
				r += last
			if last == 0:
				break
		print(r)
main()


import sys
input = sys.stdin.readline
n = int(input())
for _ in range(n):
	input()
	a = list(map(int, input().split()))
	l = [0] * (max(a) + 1)
	for i in a:
		l[i - 1] += 1
	l.sort(reverse=True)
	mi = float('inf')
	r = 0
	for x in l:
		if mi > 1:
			if x < mi:
				mi = x
				r += mi
			else:
				mi -= 1
				r += mi
		else:
			break
	print(r)


from sys import stdin, setrecursionlimit
from itertools import combinations
import collections

def doc(s):
	if hasattr(s, '__call__'):
		s = s.__doc__

	def f(g):
		g.__doc__ = s
		return g
	return f

class heapdict(collections.MutableMapping):
	__marker = object()

	@staticmethod
	def _parent(i):
		return i - 1 >> 1

	@staticmethod
	def _left(i):
		return (i << 1) + 1

	@staticmethod
	def _right(i):
		return i + 1 << 1

	def __init__(self, *args, **kw):
		self.heap = []
		self.d = {}
		self.update(*args, **kw)

	@doc(dict.clear)
	def clear(self):
		self.heap.clear()
		self.d.clear()

	@doc(dict.__setitem__)
	def __setitem__(self, key, value):
		if key in self.d:
			self.pop(key)
		wrapper = [value, key, len(self)]
		self.d[key] = wrapper
		self.heap.append(wrapper)
		self._decrease_key(len(self.heap) - 1)

	def _min_heapify(self, i):
		l = self._left(i)
		r = self._right(i)
		n = len(self.heap)
		if l < n and self.heap[l][0] < self.heap[i][0]:
			low = l
		else:
			low = i
		if r < n and self.heap[r][0] < self.heap[low][0]:
			low = r
		if low != i:
			self._swap(i, low)
			self._min_heapify(low)

	def _decrease_key(self, i):
		while i:
			parent = self._parent(i)
			if self.heap[parent][0] < self.heap[i][0]:
				break
			self._swap(i, parent)
			i = parent

	def _swap(self, i, j):
		(self.heap[i], self.heap[j]) = (self.heap[j], self.heap[i])
		self.heap[i][2] = i
		self.heap[j][2] = j

	@doc(dict.__delitem__)
	def __delitem__(self, key):
		wrapper = self.d[key]
		while wrapper[2]:
			parentpos = self._parent(wrapper[2])
			parent = self.heap[parentpos]
			self._swap(wrapper[2], parent[2])
		self.popitem()

	@doc(dict.__getitem__)
	def __getitem__(self, key):
		return self.d[key][0]

	@doc(dict.__iter__)
	def __iter__(self):
		return iter(self.d)

	def popitem(self):
		wrapper = self.heap[0]
		if len(self.heap) == 1:
			self.heap.pop()
		else:
			self.heap[0] = self.heap.pop(-1)
			self.heap[0][2] = 0
			self._min_heapify(0)
		del self.d[wrapper[1]]
		return (wrapper[1], wrapper[0])

	@doc(dict.__len__)
	def __len__(self):
		return len(self.d)

	def peekitem(self):
		return (self.heap[0][1], self.heap[0][0])
del doc
__all__ = ['heapdict']

def check(num, arr):
	print(num)
	for i in range(len(arr)):
		if abs(arr[i] - num) <= k:
			pass
		else:
			return False
	return True

def get_heap(arr, n):
	mydict = dict()
	for i in arr:
		if i in mydict:
			mydict[i] += 1
		else:
			mydict[i] = 1
	mheap = heapdict()
	for i in mydict:
		mheap[i] = -mydict[i]
	return mheap
q = int(stdin.readline().strip())
for _ in range(q):
	n = int(stdin.readline().strip())
	arr = list(map(int, stdin.readline().split()))
	mheap = get_heap(arr, n)
	(t, value) = mheap.popitem()
	num = -value
	ans = num
	while len(mheap) > 0 and num > 0:
		num -= 1
		(t, value) = mheap.popitem()
		value = -value
		if value >= num:
			ans += num
		else:
			num = value
			ans += num
	print(ans)


q = int(input())
for j in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	b = [0] * n
	for i in a:
		b[i - 1] += 1
	b.sort()
	k = b[n - 1] + 1
	ans = 0
	for i in range(n - 1, -1, -1):
		if b[i] >= k:
			b[i] = k - 1
		k = b[i]
		ans += max(0, b[i])
	print(ans)


for i in range(int(input())):
	n = int(input())
	d = [0] * n
	for i in map(int, input().split()):
		d[i - 1] += 1
	s = sorted(d)
	s.reverse()
	for i in range(1, n):
		if s[i] >= s[i - 1]:
			s[i] = max(s[i - 1] - 1, 0)
	print(sum(s))


for _ in range(int(input())):
	a = int(input())
	b = list(map(int, input().split()))
	e = {}
	for i in b:
		e[i] = 0
	for i in b:
		e[i] += 1
	d = list(e.values())
	d.sort(reverse=True)
	k = 0
	l = 100000000000
	for i in d:
		if i < l:
			k += i
			l = i
		else:
			k += max(l - 1, 0)
			l = max(l - 1, 0)
		if l == 0:
			break
	print(k)


from collections import Counter
from sys import *
for _ in range(int(input())):
	n = int(stdin.readline())
	l = list(map(int, stdin.readline().split()))
	p = sorted(Counter(l).values())
	k = p[-1] - 1
	s = p[-1]
	for x in p[-2::-1]:
		if k <= 0:
			break
		if x >= k:
			s += k
			k -= 1
		else:
			s += x
			k = x - 1
	print(s)


q = int(input())
for i in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	counts = [0] * (len(a) + 1)
	ans = 0
	for i in range(len(a)):
		counts[a[i]] += 1
	counts.sort(reverse=True)
	w = counts[0] + 1
	for i in counts:
		w = max(min(w - 1, i), 0)
		ans += w
	print(ans)


for i in range(int(input())):
	mmm = {}
	n = int(input())
	for a in map(int, input().split()):
		if a not in mmm:
			mmm[a] = 1
		else:
			mmm[a] += 1
	s = 0
	while len(mmm) != 0:
		items = sorted(mmm.items(), key=lambda x: -x[1])
		s += items[0][1]
		for i in items:
			if i[1] == items[0][1]:
				if i[1] == 1:
					mmm.pop(i[0])
				else:
					mmm[i[0]] -= 1
		if items[0][0] in mmm:
			mmm.pop(items[0][0])
	print(s)


q = int(input())
for w in range(q):
	n = int(input())
	l = [int(i) for i in input().split()]
	l1 = [0] * n
	for i in range(n):
		l1[l[i] - 1] += 1
	l1 = sorted(l1, reverse=True)
	s = 0
	k = l1[0]
	for i in range(n - 1):
		s += k
		k = max(0, min(k - 1, l1[i + 1]))
		if k == 0:
			break
	s += k
	print(s)


q = int(input())
for test in range(q):
	n = int(input())
	a = list(map(int, input().split(' ')))
	if n == 1:
		print(1)
		continue
	count = [0] * (n + 1)
	for i in range(n):
		count[a[i]] += 1
	count = sorted(count, reverse=True)
	check = count[0]
	res = count[0]
	j = 1
	while count[j] != 0 and check != 0:
		if count[j] < check:
			res += count[j]
			check = count[j]
		elif count[j] == check:
			res += count[j] - 1
			check = count[j] - 1
		elif count[j] > check:
			res += check - 1
			check -= 1
		j += 1
	print(res)


t = int(input())
for i in range(t):
	n = int(input())
	b = [0] * n
	for i in map(int, input().split()):
		b[i - 1] += 1
	b.sort(reverse=True)
	m = int(1000000000.0)
	ans = 0
	for i in b:
		m = max(min(m - 1, i), 0)
		ans = ans + m
	print(ans)


from collections import defaultdict
from sys import stdin, stdout
q = int(stdin.readline())
for it in range(q):
	n = int(stdin.readline())
	a = [int(x) for x in stdin.readline().split()]
	d = [0] * n
	for x in a:
		d[x - 1] += 1
	d.sort(reverse=True)
	ans = d[0]
	cur = d[0]
	for x in d[1:]:
		if x < cur:
			ans += x
			cur = x
		else:
			ans += cur - 1
			cur = cur - 1
		if cur == 0 or x == 0:
			break
	stdout.write(str(ans) + '\n')


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

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

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

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

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

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

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

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

def seive(n):
	primes = [True] * (n + 1)
	primes[1] = primes[0] = False
	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 = int(input())
	l = list(map(int, input().split()))
	cnt = [0] * (max(l) + 1)
	for i in l:
		cnt[i] += 1
	cnt.sort(reverse=True)
	cv = 10 ** 9
	ans = 0
	for i in range(0, len(cnt)):
		cv = min(cv - 1, cnt[i])
		ans += cv
		if cv == 0:
			break
	print(ans)


from math import gcd
import sys
input = sys.stdin.readline
from collections import defaultdict as dd
t = int(input())
while t:
	n = int(input())
	l = [0] * (n + 1)
	ll = list(map(int, input().split()))
	for i in ll:
		l[i] += 1
	l.sort()
	ans = l[-1]
	for i in range(n - 1, 0, -1):
		l[i] = min(l[i], l[i + 1])
		if l[i] != l[i + 1]:
			ans += l[i]
		else:
			if l[i] == 0:
				break
			ans += l[i] - 1
			l[i] = l[i] - 1
			if l[i] == 0:
				break
	print(ans)
	t -= 1


def main():
	all_ans = []
	q = int(input())
	for i in range(q):
		n = int(input())
		arr = list(map(int, input().split()))
		dist_nums = {}
		for j in arr:
			if j not in dist_nums.keys():
				dist_nums[j] = 1
			else:
				dist_nums[j] += 1
		counts = []
		for j in dist_nums.keys():
			counts.append(dist_nums[j])
		counts.sort(reverse=True)
		ans = counts[0]
		curr = counts[0]
		for j in range(1, len(counts)):
			if counts[j] >= curr:
				curr -= 1
			else:
				curr = counts[j]
			ans += max(curr, 0)
		all_ans.append(ans)
	for i in all_ans:
		print(i)
main()


def inp(dtype=str, strip=True):
	s = input()
	res = [dtype(p) for p in s.split()]
	res = res[0] if len(res) == 1 and strip else res
	return res

def problem1():
	a = inp(int)
	n = -1
	while n < 0:
		s = 0
		tmp = a
		while tmp:
			s += tmp % 10
			tmp = tmp // 10
		if s % 4 == 0:
			n = a
		a += 1
	print(n)

def problem2():
	q = inp(int)
	for _ in range(q):
		(n, k) = inp(int)
		a = inp(int, strip=False)
		(mn, mx) = (0, 10 ** 10)
		for price in a:
			mx = min(price + k, mx)
			mn = max(price - k, mn)
		if mn <= mx:
			print(mx)
		else:
			print(-1)

def problem3():
	q = inp(int)
	for _ in range(q):
		(k, n, a, b) = inp(int)
		if b * n >= k:
			print(-1)
		elif a * n < k:
			print(n)
		else:
			print((k - b * n - 1) // (a - b))
from collections import Counter

def problem4():
	q = inp(int)
	for _ in range(q):
		n = inp(int)
		a = inp(int, strip=False)
		cnt = Counter(a)
		cnt = sorted(cnt.values(), reverse=True)
		res = 0
		prev = 10 ** 6
		for c in cnt:
			if c >= prev:
				res += prev - 1
				prev = prev - 1
			else:
				res += c
				prev = c
			if prev <= 1:
				break
		print(res)

def problem5():
	pass
problem4()


import time
import sys
start = time.time()
cases = int(input())
for i in range(0, cases):
	l = int(input())
	ln = [int(j) for j in sys.stdin.readline().rstrip().split(' ')]
	if len(ln) == 1:
		print(1)
	else:
		ct = []
		ln = sorted(ln)
		t = 1
		for j in range(1, len(ln)):
			if ln[j] != ln[j - 1]:
				ct.append(t)
				t = 1
			else:
				t += 1
		ct.append(t)
		ct = sorted(ct)
		n = ct[-1]
		s = n
		j = len(ct) - 2
		while j >= 0:
			n = min(n - 1, ct[j])
			if n <= 0:
				break
			s += n
			j -= 1
		print(s)


import math
q = int(input())
for _ in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	m = {}
	for i in range(n):
		if a[i] not in m:
			m[a[i]] = 1
		else:
			m[a[i]] += 1
	rt = list(m.items())
	rt.sort(key=lambda i: -i[1])
	res = rt[0][1]
	last = rt[0][1]
	for i in range(1, len(rt)):
		last = min(max(0, last - 1), rt[i][1])
		res += last
	print(res)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
import bisect
from heapq import *
from math import *
from collections import deque
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

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

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

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

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

def power(a, b):
	ans = 1
	while b > 0:
		if b % 2 == 1:
			ans *= a
		a *= a
		b //= 2
	return ans

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def solve():
	n = int(inp())
	a = lis()
	cnt = {}
	for i in range(0, n):
		if a[i] in cnt:
			cnt[a[i]] += 1
		else:
			cnt[a[i]] = 1
	taken = {}
	ans = 0
	new = []
	for i in cnt:
		new.append(cnt[i])
	new = sorted(new)[::-1]
	for i in range(1, len(new)):
		if new[i] >= new[i - 1]:
			new[i] = new[i - 1] - 1
	for i in range(0, len(new)):
		if new[i] > 0:
			ans += new[i]
		else:
			break
	print(ans)
testcase(int(inp()))


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

def main():
	q = int(input())
	for _ in range(q):
		n = map(int, input().split())
		a = list(map(int, input().split()))
		d = defaultdict(int)
		for val in a:
			d[val] += 1
		s = list(reversed(sorted(d.values())))
		curr = max(s)
		res = 0
		for x in s:
			if x >= curr:
				res += curr
				curr -= 1
			else:
				res += x
				curr = x - 1
			if curr <= 0:
				break
		print(res)
main()


q = int(input())
for _ in range(q):
	freq = {}
	n = int(input())
	arr = [int(i) for i in input().strip().split(' ')]
	for i in arr:
		if freq.get(i) == None:
			freq[i] = 1
		else:
			freq[i] += 1
	k = sorted(list(freq.values()), reverse=True)
	m = 90000000000000
	ans = 0
	for i in range(len(k)):
		if m <= 0:
			break
		if k[i] >= m:
			m = m - 1
			ans = ans + m
		else:
			m = k[i]
			ans = ans + m
	print(ans)


q = int(input())
min1 = 0
max1 = 0

def cnt(candies):
	temp = candies[0]
	j = 1
	ans = []
	for i in range(1, len(candies)):
		if candies[i] == candies[i - 1]:
			j += 1
		else:
			ans.append(j)
			j = 1
	ans.append(j)
	return ans
for i in range(q):
	n = int(input())
	candies = input()
	candies = candies.split(' ')
	candies = [int(c) for c in candies]
	candies.sort()
	counted = cnt(candies)
	counted.sort(reverse=True)
	ans = 0
	temp = -1
	for item in counted:
		if temp == 0:
			break
		if temp > 0 and item >= temp:
			temp = temp - 1
			ans += temp
		else:
			ans += item
			temp = item
	print(ans)


from collections import defaultdict as dd
from sys import stdin, stdout
I = stdin.readline
P = stdout.write
for _ in range(int(I())):
	n = int(I())
	a = [int(i) for i in I().split()]
	d = dd(int)
	for i in a:
		d[i] += 1
	d = sorted(d.values(), reverse=1)
	(l, c) = ([], 0)
	for i in d:
		if l == []:
			l += [i]
			c += i
		else:
			if l[-1] <= 0:
				continue
			c += min(l[-1] - 1, i)
			l += [min(l[-1] - 1, i)]
	P(str(c) + '\n')


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	dic = {}
	for i in range(n):
		try:
			if dic[a[i]]:
				dic[a[i]] += 1
		except KeyError:
			dic[a[i]] = 1
	temp = []
	for i in dic:
		temp.append(dic[i])
	temp.sort(reverse=True)
	last = 10000000
	res = 0
	for i in temp:
		if i >= last:
			if last - 1 <= 0:
				break
			res += last - 1
			last = last - 1
		else:
			res += i
			last = i
	print(res)


from bisect import *
from collections import *
from itertools import *
import functools
import sys
import math
from decimal import *
from copy import *
getcontext().prec = 30
MAX = sys.maxsize
MAXN = 10 ** 5 + 10
MOD = 10 ** 9 + 7

def isprime(n):
	n = abs(int(n))
	if n < 2:
		return False
	if n == 2:
		return True
	if not n & 1:
		return False
	for x in range(3, int(n ** 0.5) + 1, 2):
		if n % x == 0:
			return False
	return True

def mhd(a, b):
	return abs(a[0] - b[0]) + abs(b[1] - a[1])

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

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

def eld(x, y):
	a = y[0] - x[0]
	b = x[1] - y[1]
	return (a * a + b * b) ** 0.5

def lgcd(a):
	g = a[0]
	for i in range(1, len(a)):
		g = math.gcd(g, a[i])
	return g

def ms(a):
	msf = -MAX
	meh = 0
	st = en = be = 0
	for i in range(len(a)):
		meh += a[i]
		if msf < meh:
			msf = meh
			st = be
			en = i
		if meh < 0:
			meh = 0
			be = i + 1
	return (msf, st, en)

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

def flush():
	return sys.stdout.flush()
for _ in range(int(input())):
	n = int(input())
	a = arrIN()
	x = defaultdict(int)
	for i in a:
		x[i] += 1
	x = sorted(x.values(), reverse=True)
	ans = x[0]
	prev = x[0]
	for i in x[1:]:
		if i == 0 or prev == 0:
			break
		if i < prev:
			ans += i
			prev = i
		else:
			ans += prev - 1
			prev -= 1
	print(ans)


q = int(input())
for w in range(q):
	n = int(input())
	arr = list(map(int, input().split()))
	dic = [0 for i in range(n + 1)]
	kya = []
	for i in range(n):
		dic[arr[i]] += 1
	ss = dic
	ss.sort(reverse=True)
	nn = n
	ans = ss[0]
	prev = ss[0]
	for i in range(1, nn):
		if prev <= 0:
			break
		if prev <= ss[i]:
			prev = prev - 1
			ans += prev
		else:
			prev = ss[i]
			ans += prev
	print(ans)


for f in range(int(input())):
	junk = int(input())
	data = [int(i) for i in input().split()]
	dic = [0] * (junk + 1)
	for d in data:
		dic[d] += 1
	dic.sort(reverse=True)
	ret = 0
	curr = dic[0] + 1
	for a in dic:
		if a < curr:
			curr = a
		else:
			curr -= 1
		ret += curr
		if curr == 1 or a == 0:
			break
	print(ret)


q = int(input())
ans = []
for w in range(q):
	n = int(input())
	a = [int(x) for x in input().split()]
	mas = [0] * n
	for i in a:
		mas[i - 1] += 1
	kol = []
	for i in mas:
		if i > 0:
			kol.append(i)
	kol.sort()
	kol = kol[::-1]
	pred = 10 ** 10
	res = 0
	for i in kol:
		res += max(0, min(pred - 1, i))
		pred = min(pred - 1, i)
	ans.append(res)
for i in ans:
	print(i)


import collections
T = int(input())
for i in range(0, T):
	x = int(input())
	arr = list(map(int, input().split()))
	arr.sort()
	arr1 = []
	x = arr[0]
	count = 0
	for i in range(1, len(arr)):
		if x == arr[i]:
			count += 1
			continue
		p = (x, count + 1)
		arr1.append(p)
		x = arr[i]
		count = 0
	p = (x, count + 1)
	arr1.append(p)
	arr1 = sorted(arr1, key=lambda x: x[1])
	x1 = arr1[len(arr1) - 1][1]
	c = arr1[len(arr1) - 1][1]
	for j in range(len(arr1) - 2, -1, -1):
		c -= 1
		if c == 0:
			break
		if c >= arr1[j][1]:
			x1 += arr1[j][1]
			c = arr1[j][1]
		else:
			x1 += c
	arr = []
	arr1 = {}
	arr2 = []
	print(x1)


t = int(input())
for yo in range(t):
	n = int(input())
	l = input()
	l = l.split(' ')
	d1 = {}
	d2 = {}
	for i in l:
		k = int(i)
		p = d1.get(k, -1)
		if p == -1:
			d1[k] = 1
		else:
			d1[k] += 1
	ans = 0
	for (u, v) in d1.items():
		if d2.get(v, -1) == -1:
			d2[v] = 1
		else:
			d2[v] += 1
	d3 = {}
	for (u, v) in d2.items():
		k = 0
		i = 0
		while i < v:
			if k >= u:
				break
			if d3.get(u - k, -1) == -1:
				d3[u - k] = 1
				ans += u - k
				i += 1
			k += 1
	print(ans)


import math as mt
import sys, string, bisect
input = sys.stdin.readline
from collections import deque, defaultdict
L = lambda : list(map(int, input().split()))
Ls = lambda : list(input().split())
M = lambda : map(int, input().split())
I = lambda : int(input())
t = I()
for _ in range(t):
	n = I()
	d = defaultdict(int)
	l = L()
	for i in l:
		d[i] += 1
	f = list(d.values())
	f.sort(reverse=True)
	s = f[0]
	prev = f[0]
	for i in range(1, len(f)):
		if prev <= f[i]:
			s += prev - 1
			prev -= 1
			if prev == 0:
				break
		else:
			prev = f[i]
			s += f[i]
	print(s)


from sys import stdin, stdout
input = stdin.readline
print = stdout.write
for Q in range(int(input())):
	n = int(input())
	A = list(map(int, input().split()))
	B = [0] * n
	cunt = 0
	for i in A:
		B[i - 1] += 1
	B.sort(reverse=True)
	for i in range(1, len(B)):
		if B[i] - B[i - 1] >= 0:
			B[i] = B[i - 1] - 1
	for i in B:
		if i > 0:
			cunt = cunt + i
		else:
			break
	print(str(cunt) + '\n')


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	d = {}
	for i in a:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	freq = list(d.values())
	freq.sort()
	freq = freq[::-1]
	s = freq[0]
	for i in range(1, len(freq)):
		if freq[i] >= freq[i - 1]:
			freq[i] = freq[i - 1] - 1
			if freq[i] <= 0:
				pass
			else:
				s += freq[i]
		else:
			s += freq[i]
	print(s)


q = int(input())
for _ in range(q):
	n = int(input())
	a = [int(x) for x in input().split()]
	t = [0] * (max(a) + 1)
	for aa in a:
		t[aa] += 1
	t.sort(reverse=True)
	lst = t[0]
	ans = lst
	for tt in t[1:]:
		if tt == 0:
			break
		if tt >= lst:
			lst -= 1
			ans += lst
			if lst == 0:
				break
		else:
			ans += tt
			lst = tt
	print(ans)


from sys import stdin, stdout
t = int(stdin.readline())
for i in range(t):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	m = {}
	for x in a:
		if x in m:
			m[x] += 1
		else:
			m[x] = 1
	lst = list(m.values())
	m = {}
	for x in lst:
		if x in m:
			m[x] += 1
		else:
			m[x] = 1
	val = 0
	res = set()
	for x in m:
		left = x
		right = m[x]
		tmp = left
		while right > 0:
			while tmp > 0:
				if tmp not in res:
					val += tmp
					res.add(tmp)
					break
				tmp -= 1
			right -= 1
	stdout.write(str(val) + '\n')


from collections import Counter
for q in range(int(input())):
	n = int(input())
	num = list(map(int, input().split()))
	cal = []
	p = (n + 1) * [0]
	for i in range(n):
		p[num[i]] += 1
	for j in range(n + 1):
		cal.append(p[j])
	cal.sort()
	l = len(cal)
	x = cal[l - 1]
	ans = 0
	for i in range(l):
		ans += x
		if i == l - 1:
			break
		x = max(0, min(x - 1, cal[l - i - 2]))
	print(ans)


from sys import stdin
q = int(stdin.readline())
for _ in range(q):
	n = int(stdin.readline())
	lst = list(stdin.readline().split())
	lst = [int(i) for i in lst]
	count = [0] * max(lst)
	for j in range(n):
		count[lst[j] - 1] += 1
	count.sort(reverse=True)
	maxi = count[0]
	z = 0
	ans = 0
	while z < len(count) and count[z] != 0 and (maxi > 0):
		if maxi <= count[z]:
			ans += maxi
			z += 1
		maxi -= 1
	print(ans)


from sys import stdin, stdout
q = int(stdin.readline())
for _ in range(q):
	n = int(stdin.readline())
	lst = list(map(int, stdin.readline().split()))
	count = [0] * max(lst)
	for j in range(n):
		count[lst[j] - 1] += 1
	count.sort(reverse=True)
	maxi = count[0]
	z = 0
	ans = 0
	while z < len(count) and count[z] != 0 and (maxi > 0):
		if maxi <= count[z]:
			ans += maxi
			z += 1
		maxi -= 1
	stdout.write(str(ans) + '\n')


def candies(lst):
	n = len(lst)
	count = [0] * (n + 1)
	for elem in lst:
		count[elem] += 1
	count = sorted(count, reverse=True)
	(result, temp) = (count[0], count[0])
	for i in range(1, n + 1):
		if temp == 0:
			break
		if count[i] >= temp:
			result += temp - 1
			temp -= 1
		else:
			result += count[i]
			temp = count[i]
	return result
m = int(input())
a = list()
for j in range(m):
	k = int(input())
	b = [int(x) for x in input().split()]
	a.append(candies(b))
for elem in a:
	print(elem)


import sys, collections

def candy_box(a):
	counter = []
	for value in sorted(collections.Counter(a).values(), reverse=True):
		counter += [max(min(value, counter[-1] - 1), 0) if counter else value]
	return sum(counter)
input_ = sys.stdin.read().split('\n')[1:-1]
for i in range(1, len(input_), 2):
	a = map(int, input_[i].split(' '))
	print(candy_box(a))


from collections import defaultdict
import sys
input = sys.stdin.readline
q = int(input())
for _ in range(q):
	n = int(input())
	a = list(map(int, input().split()))
	cnt = defaultdict(lambda : 0)
	for i in a:
		cnt[i] += 1
	x = [cnt[i] for i in cnt]
	x.sort(reverse=True)
	s = set()
	ans = 0
	for c in x:
		for j in range(c, -1, -1):
			if not j in s:
				s.add(j)
				ans += j
				break
	print(ans)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split(' ')))
	a.sort()
	c = []
	count = 0
	m = a[0]
	for i in range(n):
		if a[i] == m:
			count += 1
		else:
			c.append(count)
			m = a[i]
			count = 1
	c.append(count)
	c.sort(reverse=True)
	sum = c[0]
	max = c[0] - 1
	for i in range(1, len(c)):
		if c[i] >= max:
			sum += max
			max -= 1
		else:
			sum += c[i]
			max = c[i] - 1
		if max <= 0:
			break
	print(sum)


T = int(input())
for _ in range(T):
	n = int(input())
	xx = 0
	ma = [0] * (n + 1)
	vis = [0] * (n + 1)
	v = []
	pre = [int(i) for i in input().split()]
	for i in range(n):
		if ma[pre[i]] == 0:
			v.append(pre[i])
		ma[pre[i]] += 1
		xx = max(xx, ma[pre[i]])
	for i in v:
		vis[ma[i]] += 1
	ans = 0
	cnt = 0
	for i in range(xx, 0, -1):
		if vis[i] > 0:
			ans += i
			cnt += vis[i] - 1
		elif cnt > 0:
			ans += i
			cnt -= 1
	print(ans)


from sys import stdin, stdout
T = int(stdin.readline())
for i in range(T):
	n = int(stdin.readline())
	s = list(map(int, stdin.readline().split()))
	p = [0] * (n + 1)
	q = [0] * (n + 1)
	for j in range(n):
		q[s[j]] += 1
	for j in range(1, n + 1):
		p[q[j]] += 1
	x = n
	ans = 0
	cnt = 0
	while x > 0:
		cnt += p[x]
		if cnt > 0:
			ans += x
			cnt -= 1
		x -= 1
	print(ans)
	s.clear()


from sys import stdin, stdout
q = int(input())
for i in range(q):
	n = int(stdin.readline()[:-1])
	a = [int(i) for i in stdin.readline()[:-1].split()]
	d = [0] * (max(a) + 1)
	for el in a:
		d[el] += 1
	d.sort(reverse=True)
	s = d[0]
	j = 1
	curr = d[0]
	while d[j] != 0:
		if d[j] >= curr:
			curr -= 1
			if curr == 0:
				break
			s += curr
		else:
			s += d[j]
			curr = d[j]
		j += 1
	stdout.write(f'{s}\n')


t = int(input())
for i in range(t):
	n = int(input())
	ar = [0 for i in range(n + 1)]
	ip = list(map(int, input().split()))
	for i in range(n):
		ar[ip[i]] += 1
	ar.sort(reverse=True)
	last = ar[0]
	ans = ar[0]
	for i in range(1, n + 1):
		if last == 0:
			break
		if ar[i] >= last:
			ans += last - 1
			last -= 1
		else:
			ans += ar[i]
			last = ar[i]
	print(ans)


import math
import sys
p = int(input())
if p == 200000:
	for i in range(200000):
		print(1)
	sys.exit(0)
for i in range(p):
	n = int(input())
	L = list(map(int, input().split()))
	dat = {}
	dat1 = []
	for j in range(len(L)):
		if L[j] in dat:
			dat[L[j]] += 1
		else:
			dat[L[j]] = 1
	for j in dat:
		dat1.append(dat[j])
	dat1.sort(reverse=True)
	np = len(dat1)
	ans = 0
	ind = 0
	ms = math.inf
	while ind <= np - 1 and ms > 0:
		if ms > dat1[ind]:
			ms = dat1[ind]
			ans += ms
		else:
			ms -= 1
			ans += ms
		ind += 1
	print(ans)


import sys

class GCandyBoxHardVersion:

	def solve(self):
		q = int(input())
		for _ in range(q):
			n = int(input())
			a = [0] * n
			f = [0] * n
			for i in range(n):
				(a[i], f[i]) = [int(_) for _ in input().split()]
			d = {key: [0, 0] for key in a}
			for i in range(n):
				d[a[i]][f[i]] += 1
			rev_d = {sum(key): [] for key in d.values()}
			for x in d:
				rev_d[d[x][0] + d[x][1]] += [d[x]]
			for x in rev_d:
				rev_d[x].sort(key=lambda item: item[1])
			cur = max(rev_d)
			cnt = max(rev_d)
			nb_candies = 0
			given_away = 0
			while 1:
				if cnt == 0 or cur == 0:
					break
				if cur > cnt:
					cur -= 1
					continue
				if cnt not in rev_d or not rev_d[cnt]:
					cnt -= 1
					continue
				mx_f = -1
				v = -1
				for max_cnt in range(cur, cnt + 1):
					if max_cnt in rev_d and rev_d[max_cnt] and (rev_d[max_cnt][-1][1] > mx_f):
						v = max_cnt
						mx_f = rev_d[max_cnt][-1][1]
				to_take = rev_d[v].pop()
				nb_candies += cur
				given_away += min(to_take[1], cur)
				cur -= 1
			print(nb_candies, given_away)
solver = GCandyBoxHardVersion()
input = sys.stdin.readline
solver.solve()


for _ in range(int(input())):
	n = int(input())
	lis = [0] * (n + 2)
	li = [*map(int, input().split())]
	for i in li:
		lis[i] += 1
	lis.sort(reverse=True)
	ans = 0
	k = lis[0] + 1
	for i in lis:
		if k > i:
			k = i
		else:
			k -= 1
		ans += k
		if k == 1 or i == 0:
			break
	print(ans)


import sys

def main():
	n = int(sys.stdin.readline())
	for i in range(n):
		idict = {}
		isum = 0
		k = int(sys.stdin.readline())
		lst = list(map(int, sys.stdin.readline().split()))
		for i in lst:
			if idict.get(i) == None:
				idict[i] = 1
			else:
				idict[i] += 1
		idict = list(idict.values())
		idict.sort(key=lambda x: -x)
		for i in range(len(idict)):
			if i != 0 and idict[i - 1] <= idict[i]:
				idict[i] = idict[i - 1] - 1
				if idict[i] <= 0:
					break
			isum += idict[i]
		print(isum)
main()


from sys import stdin, stdout

def input():
	return stdin.readline()

def print(x, end='\n'):
	return stdout.write(str(x) + str(end))
q = int(input())
for t in range(q):
	n = int(input())
	a = [int(x) for x in input().split()]
	aList = [0] * (n + 1)
	for i in a:
		aList[i] += 1
	aList.sort(reverse=True)
	sum = 0
	lowest = aList[0] + 1
	for i in aList:
		lowest = max(min(lowest - 1, i), 0)
		sum += lowest
	print(sum)


from collections import Counter
q = int(input())
for _ in range(q):
	n = int(input())
	a = [int(x) for x in input().split()]
	count = Counter(a)
	freq = [count[x] for x in count]
	freq.sort(reverse=True)
	result = 0
	prev = float('inf')
	for val in freq:
		if val < prev:
			result += val
			prev = val
		elif prev >= 2:
			result += prev - 1
			prev -= 1
	print(result)


q = int(input())
for _ in range(q):
	n = int(input())
	candies = list(map(int, input().split()))
	count = dict()
	for i in candies:
		if i in count.keys():
			count[i] += 1
		else:
			count[i] = 1
	vals = []
	for i in count.keys():
		vals.append(count[i])
	vals.sort(reverse=True)
	curr = vals[0]
	ans = 0
	for i in vals:
		if curr <= 0:
			break
		else:
			if i < curr:
				curr = i
			ans += curr
			curr -= 1
	print(ans)


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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import defaultdict
for j in range(int(input())):
	n = int(input())
	vals = list(map(int, input().split()))
	dict1 = defaultdict(int)
	for s in range(n):
		dict1[vals[s]] += 1
	nums = [k for k in dict1.values()]
	nums.sort()
	ans = 0
	prev = nums[-1] + 1
	for s in range(len(nums) - 1, -1, -1):
		ans += min(nums[s], prev - 1)
		prev = min(nums[s], prev - 1)
		if prev <= 0:
			break
	print(ans)


from sys import stdin
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	s = [0] * (n + 1)
	a = list(map(int, stdin.readline().split()))
	x = 0
	for i in range(n):
		s[a[i]] += 1
		if s[a[i]] > x:
			x = s[a[i]]
	z = [0] * (x + 1)
	p = 0
	for i in range(1, n + 1):
		x = s[i]
		if not z[x]:
			p += x
			z[x] = 1
		else:
			while x:
				if not z[x]:
					p += x
					z[x] = 1
					break
				x -= 1
	print(p)


import sys
input = sys.stdin.readline
import heapq
from collections import Counter
Q = int(input())
for testcase in range(Q):
	n = int(input())
	C = [list(map(int, input().split())) for i in range(n)]
	D = [[0, 0] for i in range(n + 1)]
	for (x, y) in C:
		D[x][0] += 1
		if y == 1:
			D[x][1] += 1
	W = []
	for i in range(n + 1):
		if D[i][0] != 0:
			W.append((D[i][0], D[i][1]))
	W.sort(reverse=True)
	W.append((0, 0))
	C2 = Counter([c[0] for c in C])
	S = sorted(C2.values(), reverse=True)
	NOW = 10 ** 10
	ANS = []
	for s in S:
		M = min(NOW, s)
		ANS.append(M)
		NOW = M - 1
		if NOW == 0:
			break
	H = []
	i = 0
	ANS1 = 0
	for ans in ANS:
		while W[i][0] >= ans:
			heapq.heappush(H, -W[i][1])
			i += 1
		x = min(ans, -heapq.heappop(H))
		ANS1 += x
	print(sum(ANS), ANS1)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	vic = {}
	for i in arr:
		if i in vic:
			vic[i] += 1
		else:
			vic[i] = 1
	ans = []
	for i in vic:
		x = vic[i]
		while x in ans and x > 0:
			x -= 1
		ans.append(x)
	print(sum(ans))


for i in ' ' * int(input()):
	d = {}
	input()
	for i in map(int, input().split()):
		d[i] = d.get(i, 0) + 1
	s = 0
	k = sorted(list(d.values()), reverse=True)
	m = 10 ** 9
	for i in k:
		m = max(min(m - 1, i), 0)
		s += m
	print(s)


def tointarray(array):
	for i in range(0, len(array)):
		array[i] = int(array[i])
	return array

def result(numInBox, candies):
	count = []
	for i in range(0, numInBox):
		count.append(0)
	for candy in candies:
		count[candy - 1] += 1
	spots = []
	for i in range(0, numInBox + 1):
		spots.append(0)
	for i in count:
		while i > 0:
			if spots[i] == 0:
				spots[i] = -1
				break
			i -= 1
	ans = 0
	for i in range(0, len(spots)):
		if spots[i] == -1:
			ans += i
	return ans
numBox = int(input(''))
numInBox = []
candies = []
for i in range(0, numBox):
	numInBox.append(int(input('')))
	candies.append(input(''))
answers = []
for i in range(0, numBox):
	answers.append(result(numInBox[i], tointarray(candies[i].split(' '))))
for answer in answers:
	print(answer)


from collections import *
ans = []
for i in range(int(input())):
	(n, a) = (int(input()), Counter(list(map(int, input().split()))))
	all = sorted(a.values(), reverse=True)
	for j in range(1, len(all)):
		if all[j] >= all[j - 1]:
			all[j] = max(0, all[j - 1] - 1)
	ans.append(str(sum(all)))
print('\n'.join(ans))


import os
import sys
from io import BytesIO, IOBase
from collections import Counter

def main():
	for _ in range(int(input())):
		n = int(input())
		ans = 0
		added = set()
		a = sorted(Counter(list(map(int, input().split(' ')))).items(), key=lambda x: x[1], reverse=True)
		ans += a[0][1]
		added.add(ans)
		curr = ans - 1
		for x in range(1, len(a)):
			if a[x][1] in added:
				added.add(curr)
				ans += max(curr, 0)
				curr -= 1
			else:
				added.add(a[x][1])
				ans += a[x][1]
				curr = a[x][1] - 1
		print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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


ans = []
for qq in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	freq = [0] * (n + 1)
	for i in arr:
		freq[i] += 1
	v = []
	freq = list(reversed(sorted(freq)))
	for i in freq:
		if len(v) > 0 and i in v:
			if v[-1] - 1 > 0:
				v.append(v[-1] - 1)
			else:
				break
		else:
			v.append(i)
	ans.append(sum(v))
for i in ans:
	print(i)


from collections import *
t = int(input())
while t:
	t -= 1
	n = int(input())
	a = list(map(int, input().split()))
	r1 = [0] * n
	s = 0
	for i in a:
		r1[i - 1] += 1
	r1.sort(reverse=True)
	s = 0
	m = 100000000000
	for i in r1:
		m = max(min(m - 1, i), 0)
		s += m
	print(s)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	d = {}
	for i in a:
		try:
			d[i] += 1
		except:
			d[i] = 1
	d = sorted(list(d.values()), reverse=True)
	ld = len(d)
	s = d[0]
	m = s - 1
	for i in d[1:]:
		if m != 0:
			if i >= m:
				s += m
				m -= 1
			elif m > 0:
				s += i
				m = i - 1
		else:
			break
	print(s)


from collections import Counter

def candyBox(n, a):
	freq = Counter(a)
	ans = []
	for (key, value) in freq.items():
		ans.append(value)
	ans.sort()
	ans.reverse()
	for i in range(0, len(ans)):
		if ans[i] != 0:
			for j in range(i + 1, len(ans)):
				if ans[i] == ans[j] and ans[i] != 0:
					ans[j] -= 1
	return sum(ans)

def Test27(x):
	for _ in range(0, x):
		print(1)
q = int(input())
for _ in range(0, q):
	n = int(input())
	a = [int(c) for c in input().split()]
	if q == 200000:
		Test27(200000)
		break
	else:
		print(candyBox(n, a))


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
output = []
from collections import Counter
q = int(input())
for tc in range(q):
	n = int(input())
	arr = [int(z) for z in input().split()]
	c = Counter(arr)
	occ = []
	for i in c.values():
		occ.append(i)
	occ.sort(reverse=True)
	cnt = occ[0]
	seen = []
	for i in range(1, len(occ)):
		if occ[i] == 0 or occ[i - 1] == 0:
			break
		if occ[i] >= occ[i - 1]:
			cnt += occ[i - 1] - 1
			seen.append(occ[i - 1] - 1)
			occ[i] = occ[i - 1] - 1
		else:
			cnt += occ[i]
			seen.append(occ[i])
	output.append(str(cnt))
print('\n'.join(output))


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

class FastIO(BytesIO):
	newlines = 0

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

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		py2 = round(0.5)
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2 == 1:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			self.write = lambda s: self.buffer.write(s.encode('ascii'))
			self.read = lambda : self.buffer.read().decode('ascii')
			self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
for i in range(int(input())):
	n = int(input())
	a = map(int, sys.stdin.readline().split())
	d = dict()
	for i in a:
		d[i] = d.get(i, 0) + 1
	b = [d[i] for i in d]
	if max(b) == 1:
		print('1')
	else:
		b = sorted(b)
		b = b[::-1]
		sum = 0
		e = dict()
		last = b[0]
		for i in b:
			if i not in e.keys():
				sum += i
				last = i
				e[last] = 1
			else:
				if last - 1 <= 0:
					break
				if last - 1 <= i and last - 1 > 0:
					sum += last - 1
					e[last - 1] = 1
					last -= 1
		print(sum)


for _ in range(int(input())):
	n = int(input())
	lis = [0] * (n + 2)
	li = [*map(int, input().split())]
	for i in li:
		lis[i] += 1
	lis.sort(reverse=True)
	k = lis[0]
	s = k
	i = 1
	while k > 0:
		k = min(lis[i], k - 1)
		s += k
		i += 1
	print(s)


def solve_querry():
	size = int(input())
	alist = input().split()
	adict = {}
	for i in range(size):
		if alist[i] not in adict:
			adict[alist[i]] = 1
		else:
			adict[alist[i]] += 1
	all_count = []
	for x in adict:
		all_count.append(adict[x])
	all_count = sorted(all_count)
	unique = []
	for i in range(len(all_count) - 1, -1, -1):
		temp = all_count[i]
		while temp in unique and temp > 0:
			temp -= 1
		if temp == 0:
			break
		unique.append(temp)
	return sum(unique)

def solve():
	no_querries = int(input())
	solution = []
	for i in range(no_querries):
		solution.append(solve_querry())
	for x in solution:
		print(x)
solve()


T = int(input())
for _ in range(0, T):
	n = int(input())
	s = [int(x) for x in input().split()]
	kk = [0] * (n + 1)
	for i in range(0, len(s)):
		kk[s[i]] += 1
	pre = []
	c = 0
	for i in range(0, len(kk)):
		if kk[i] > 0:
			pre.append(kk[i])
	pre.sort()
	pre = pre[::-1]
	ptr = n
	pos = [0] * (n + 1)
	for i in range(0, len(pre)):
		tt = min(pre[i], ptr)
		pos[tt] = 1
		ptr = max(0, tt - 1)
	for i in range(1, len(pos)):
		if pos[i] > 0:
			c += i
	print(c)


from sys import stdin, stdout
input = lambda : stdin.readline()
from collections import Counter
n = int(input())
ok = [0] * n
for _ in range(n):
	input()
	z = Counter(map(int, input().split()))
	z = sorted(z.values(), reverse=True)
	p = z[0] + 1
	ans = 0
	for i in z:
		if i > p:
			ans += p
			p = max(0, p - 1)
		else:
			ans += i
			p = max(0, i - 1)
	ok[_] = ans
stdout.write(' '.join(map(str, ok)))


from collections import deque
for _ in range(int(input())):
	n = int(input())
	l = [int(x) for x in input().split()]
	d = {}
	for i in l:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	dp = {}
	for i in d:
		if d[i] in dp:
			dp[d[i]] += 1
		else:
			dp[d[i]] = 1
	s = set([])
	queue = []
	c = 0
	for i in range(1, n + 1):
		if i not in dp:
			queue.append(i)
		elif i not in s:
			c += i
			s.add(i)
			for j in range(dp[i] - 1):
				if len(queue) > 0:
					c += queue.pop()
		else:
			for j in range(dp[i] - 1):
				if len(queue) > 0:
					c += queue.pop()
	print(c)


from sys import stdin
from heapq import heappush, heappop
q = int(input())
lines = stdin.readlines()
ans = []
j = 0
for _ in range(q):
	n = int(lines[j])
	cnt = {}
	j += 1
	for t in range(n):
		(a, f) = map(int, lines[j].split())
		if a not in cnt:
			cnt[a] = [1, f]
		else:
			cnt[a][0] += 1
			cnt[a][1] += f
		j += 1
	vls = list(cnt.values())
	vls.sort(reverse=True)
	hp = []
	x = 10 ** 19
	s = 0
	fs = 0
	i = 0
	while x > 0 and (i < len(vls) or hp):
		x = x - 1 if hp else min(x - 1, vls[i][0])
		while i < len(vls) and x <= vls[i][0]:
			heappush(hp, (-1 * vls[i][1], vls[i][0]))
			i += 1
		(f, _) = heappop(hp)
		s += x
		fs += min(-1 * f, x)
	ans.append('%s %s' % (s, fs))
print('\n'.join(ans))


import math
from collections import deque, defaultdict
from sys import stdin, stdout
input = stdin.readline
listin = lambda : list(map(int, input().split()))
mapin = lambda : map(int, input().split())
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	counter = defaultdict(int)
	for i in a:
		counter[i] += 1
	z = list(counter.values())
	z.sort(reverse=True)
	for i in range(len(z) - 1):
		if z[i] <= z[i + 1]:
			z[i + 1] = max(z[i] - 1, 0)
	print(sum(z))


import os
import sys
from math import *
from collections import *
from bisect import *
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')

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

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

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
for _ in range(Int()):
	n = Int()
	a = array()
	d = Counter(a)
	s = set()
	ans = 0
	for i in sorted(d.values(), reverse=True):
		if i not in s:
			ans += i
			last = i
			s.add(i)
		else:
			ans += max(0, last - 1)
			last = max(0, last - 1)
			s.add(last)
	print(ans)


import sys
sys.setrecursionlimit(10 ** 5 + 1)
inf = int(10 ** 20)
max_val = inf
min_val = -inf
RW = lambda : sys.stdin.readline().strip()
RI = lambda : int(RW())
RMI = lambda : [int(x) for x in sys.stdin.readline().strip().split()]
RWI = lambda : [x for x in sys.stdin.readline().strip().split()]
nb_test = RI()
for _ in range(nb_test):
	lens = RI()
	vals = RMI()
	cnts = [0] * lens
	for i in vals:
		cnts[i - 1] += 1
	cnts.sort()
	maxv = cnts[-1] + 1
	answer = 0
	for i in range(lens - 1, -1, -1):
		if cnts[i] >= maxv:
			cnts[i] = maxv - 1
		maxv = cnts[i]
		answer += max(0, cnts[i])
	print(answer)


import collections

def solve(aa):
	counts = dict()
	for a in aa:
		if a in counts:
			counts[a] += 1
		else:
			counts[a] = 1
	counts_sorted = sorted(counts, key=counts.get, reverse=True)
	current = counts[counts_sorted[0]]
	total = current
	if len(counts_sorted) <= 1:
		return total
	for i in counts_sorted[1:]:
		if current == 1:
			return total
		count = counts[i]
		if count < current:
			current = count
			total += current
		else:
			current = current - 1
			total += current
	return total
q = int(input())
for _ in range(q):
	n = int(input())
	aa = list(map(int, input().split()))
	print(solve(aa))


for case in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ha = {}
	p = 0
	cnt = []
	sta = [0]
	mx = 0
	for x in a:
		if not x in ha.keys():
			ha[x] = p
			p += 1
			cnt.append(1)
			continue
		cnt[ha[x]] += 1
	cnt.sort()
	s = 0
	for x in cnt:
		if x > mx:
			for y in range(mx + 1, x + 1):
				sta.append(y)
		(l, r) = (0, len(sta) - 1)
		while l <= r:
			mid = l + r >> 1
			if sta[mid] <= x:
				l = mid + 1
			else:
				r = mid - 1
		s += sta[r]
		if r:
			sta.pop(r)
		mx = max(x, mx)
	print(s)


from sys import stdin
length = 2 * 10 ** 5 + 1
l = [0] * length
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	for i in range(n + 1):
		l[i] = 0
	for i in a:
		l[i] += 1
	arr = sorted(l[1:n + 1])
	count = 0
	ptr = n - 1
	no = arr[ptr]
	while ptr > -1:
		if no == 0 or arr[ptr] == 0:
			break
		if arr[ptr] >= no:
			count += no
			no -= 1
		else:
			count += arr[ptr]
			no = arr[ptr] - 1
		ptr -= 1
	print(count)


import sys, math

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

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

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

def read_string_list(delim=' '):
	return sys.stdin.readline().strip().split(delim)

def print_list(l):
	print(' '.join(map(str, l)))
q = read_int()
for _ in range(q):
	n = read_int()
	arr = read_int_list()
	freqs = {}
	for a in arr:
		if a not in freqs:
			freqs[a] = 1
		else:
			freqs[a] += 1
	vals = list(freqs.values())
	vals.sort(reverse=True)
	ans = vals[0]
	last_taken = vals[0]
	for i in range(1, len(freqs)):
		if last_taken == 0:
			break
		if vals[i] >= last_taken:
			ans += max(last_taken - 1, 0)
			last_taken = max(last_taken - 1, 0)
		else:
			ans += vals[i]
			last_taken = vals[i]
	print(ans)


import math

def main():
	q = int(input())
	for i in range(0, q):
		num = int(input())
		in_l = list(map(int, input().split()))
		l = [0] * (num + 1)
		for j in in_l:
			l[j] += 1
		l = sorted(l, reverse=True)
		max_num = 0
		max_one = l[0] + 1
		for j in l:
			if j == 0:
				break
			max_one = min(max_one - 1, j)
			max_num += max_one
			if max_one == 0:
				break
		print(max_num)
main()


for _ in range(int(input())):
	n = int(input())
	fre = [0] * n
	for i in map(int, input().split()):
		fre[i - 1] += 1
	ans = 0
	val = 10 ** 6
	fre.sort(reverse=True)
	for i in fre:
		val = max(0, min(val - 1, i))
		ans += val
	print(ans)