Candy Box (hard version) (Codeforces 1183G)
Tags: Greedy, sortings

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.  

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.

Sample Inputs:
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

Sample Outputs:
3 3
3 3
9 5

Solution (Python):
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')
if __name__ == '__main__':
    main()

Solution (Python):
def naiveSolve():
    return

def solve():
    return
import heapq

def main():
    t = int(input())
    allans = []
    for _ in range(t):
        n = int(input())
        totalCnt = [0] * (n + 1)
        fCnt = [0] * (n + 1)
        for __ in range(n):
            (a, f) = readIntArr()
            totalCnt[a] += 1
            fCnt[a] += f
        total_f = []
        for typee in range(1, n + 1):
            if totalCnt[typee] > 0:
                total_f.append((totalCnt[typee], fCnt[typee]))
        total_f.sort(reverse=True)
        total_f.append((0, 0))
        ans1 = 0
        ans2 = 0
        currMinCnt = total_f[0][0]
        i = 0
        maxHeap = []
        while currMinCnt > 0:
            while i < n and total_f[i][0] >= currMinCnt:
                heapq.heappush(maxHeap, -total_f[i][1])
                i += 1
            if len(maxHeap) > 0:
                ans1 += currMinCnt
                ans2 += min(currMinCnt, abs(heapq.heappop(maxHeap)))
            currMinCnt -= 1
        allans.append((ans1, ans2))
    multiLineArrayOfArraysPrint(allans)
    return
import sys
input = sys.stdin.buffer.readline

def oneLineArrayPrint(arr):
    print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
    print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
    print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
    return [int(x) for x in input().split()]

def makeArr(defaultValFactory, dimensionArr):
    dv = defaultValFactory
    da = dimensionArr
    if len(da) == 1:
        return [dv() for _ in range(da[0])]
    else:
        return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(x):
    print('{}'.format(x))
    sys.stdout.flush()
    return int(input())

def answerInteractive(ans):
    print('! {}'.format(ans))
    sys.stdout.flush()
inf = float('inf')
from math import gcd, floor, ceil
for _abc in range(1):
    main()

Solution (Python):
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')
if __name__ == '__main__':
    main()