This problem is a version of problem D from the same contest with some additional constraints and tasks.

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.

You really like some of the candies and don't want to include them into the gift, but you want to eat them yourself instead. For each candy, a number $f_i$ is given, which is equal to $0$ if you really want to keep $i$-th candy for yourself, or $1$ if you don't mind including it into your gift. It is possible that two candies of the same type have different values of $f_i$.

You want your gift to be as large as possible, but you don't want to include too many of the candies you want to eat into the gift. So, you want to calculate the maximum possible number of candies that can be included into a gift, and among all ways to choose maximum number of candies, you want to maximize the number of candies having $f_i = 1$ in your gift.

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.

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

Then $n$ lines follow, each containing two integers $a_i$ and $f_i$ ($1 \le a_i \le n$, $0 \le f_i \le 1$), where $a_i$ is the type of the $i$-th candy, and $f_i$ denotes whether you want to keep the $i$-th candy for yourself ($0$ if you want to keep it, $1$ if you don't mind giving it away).

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


-----Output-----

For each query print two integers:

  the maximum number of candies in a gift you can compose, according to the constraints in the statement;  the maximum number of candies having $f_i = 1$ in a gift you can compose that contains the maximum possible number of candies.  


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

Output
3 3
3 3
9 5



-----Note-----

In the first query, you can include two candies of type $4$ and one candy of type $5$. All of them have $f_i = 1$ and you don't mind giving them away as part of the gift.

Source: codeforces | Difficulty: HARD
Tags: Sorting

Implementation

Greedy algorithms


Solutions:
from collections import defaultdict
import heapq
import sys
input = sys.stdin.readline
q = int(input())
for _ in range(q):
	n = int(input())
	cnt = defaultdict(lambda : 0)
	f = defaultdict(lambda : 0)
	for _ in range(n):
		(ai, fi) = map(int, input().split())
		cnt[ai] += 1
		f[ai] += fi
	x = [[cnt[i], i] for i in cnt]
	x.sort(reverse=True)
	s = set()
	t = []
	m = 0
	for (c, i) in x:
		for j in range(c, 0, -1):
			if not j in s:
				s.add(j)
				t.append(j)
				m += j
				break
	x.append([0, 0])
	h = []
	fc = 0
	j = 0
	for i in t:
		while True:
			(ck, k) = x[j]
			if ck >= i:
				heapq.heappush(h, -f[k])
				j += 1
			else:
				break
		fc -= max(heapq.heappop(h), -i)
	print(m, fc)


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)


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


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) = list(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

def __starting_point():
	main()
__starting_point()


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


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)


import os
import sys
import math
from io import BytesIO, IOBase
import io
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
from collections import Counter
import threading
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

class SegmentTree:

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

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

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

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

	def __len__(self):
		return self._len

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

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

class SegmentTree1:

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

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

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

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

	def __len__(self):
		return self._len

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

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

class Factorial:

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

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

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

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

class Combination:

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

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

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

class DSU:

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

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

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

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

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

class LazySegTree:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

def memodict(f):

	class memodict(dict):

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

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

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

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

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

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

def binarySearch1(arr, n, key):
	left = 0
	right = n - 1
	mid = 0
	res = -1
	while left <= right:
		mid = (right + left) // 2
		if arr[mid] > key:
			right = mid - 1
		else:
			res = mid
			left = mid + 1
	return res
from heapq import heapify, heappush, heappop
t = 1
t = int(input())
for _ in range(t):
	n = int(input())
	d = dict()
	for i in range(n):
		(num, f) = map(int, input().split())
		if num in d:
			d[num][0] += 1
		else:
			d[num] = [1, 0]
		if f:
			d[num][1] += 1
	a = []
	for i in d:
		a.append(d[i])
	(ans, good) = (0, 0)
	a.sort()
	h = []
	heapify(h)
	j = len(a) - 1
	for i in range(n, 0, -1):
		while j >= 0 and a[j][0] >= i:
			heappush(h, [-a[j][1], a[j][0]])
			j -= 1
		if h:
			(favour, total) = heappop(h)
			favour = -favour
			good += min(favour, i)
			ans += i
	print(ans, good)


def addInDict(x, y):
	nonlocal 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():
	nonlocal 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():
	nonlocal 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) = list(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)


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


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


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


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


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)