1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <iostream>

using namespace std;

int* counts;
int* keys;
int n;

void heapify(int i, int N) {
	int maxIndex = i;
	int left = 2 * i + 1, right = 2 * i + 2;
	if (left < N && counts[keys[maxIndex]] < counts[keys[left]] ) maxIndex = left;
	if (right < N && counts[keys[maxIndex]]  < counts[keys[right]] ) maxIndex = right;
	if (maxIndex != i) {
		swap(keys[maxIndex], keys[i]);
		heapify(maxIndex, N);
	}
}

void heapSort() {
	for (int i = n / 2 - 1; i >= 0; i--) heapify(i, n);

	for (int i = n - 1; i >= 0; i--) {
		swap(keys[0], keys[i]);
		heapify(0, i); //Notice, that the size of heap decreases each iteration
	}
}

int main()
{
    cin >> n;
    counts = new int[n + 1];
    keys = new int[n + 1];

    for(int i = 0; i <= n; i++){
        keys[i] = i;
    }
    std::fill(counts, counts + n + 1, 0);

    int input;
    for (int i = 0; i < n; i++){
        cin >> input;
        counts[input]++;
    }
    n++;
    heapSort();
    n--;

    int res = 1;
    int numsToArrs = 0;
    int leftNums = n;

    for (int i = n; i > 0; i--){
        leftNums -= counts[keys[i]];
        if (counts[keys[i]] > leftNums - numsToArrs){
            break;
        }
        else{
            res++;
            numsToArrs += (counts[keys[i]] - 1);
        }

    }

    cout << res;

    delete [] counts;
    delete [] keys;

    return 0;
}