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.

Difficulty: introductory

Starter code:

Solutions:
# @author 

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

            # print(rev_d)

            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()
                # rev_d[cnt] -= 1
                nb_candies += cur
                given_away += min(to_take[1], cur)
                cur -= 1
                # rev_d[cnt - cur] += 1
            print(nb_candies, given_away)

solver = GCandyBoxHardVersion()
input = sys.stdin.readline

solver.solve()


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)
##    print('d=', d)
##    print('d2=', d2)
    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
##    print('d4=', d4)
    d4Keys = list(d4.keys())
    d4Keys.sort(reverse = True)
##    print('d4Keys=', d4Keys)
    
    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))
    #print(W)

    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

    #print(ANS,sum(ANS))

    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)
            
            

        

    


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 (list(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 list(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
	#ind=len(l)-1
	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)

# coding: utf-8
# Your code here!
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)  # where not still used
    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

        # print("phase: ", ording)
        # print("que: ", que)
        # print("stocked: ", stocked)
        # print("border: ", border)
        # print("\n")
        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()