#C5500. Top Frequent Elements
Top Frequent Elements
Top Frequent Elements
You are given an array of integers and a number \(x\). Your task is to find the \(x\) most frequently occurring elements in the array. The elements should be listed in descending order of frequency. If two elements have the same frequency, the smaller element should come first.
Formal Definition:
Let \(f(a)\) denote the frequency of element \(a\) in the array. You need to choose \(x\) elements such that if \(a\) and \(b\) are chosen, and \(f(a) > f(b)\), then \(a\) comes before \(b\); if \(f(a) = f(b)\) then \(a < b\) implies \(a\) comes before \(b\).
Implement your solution to read from stdin and write the result to stdout for each test case.
inputFormat
The first line contains a single integer \(T\) denoting the number of test cases.
Each test case consists of three lines:
- The first line contains an integer \(n\), the number of elements in the array.
- The second line contains \(n\) space-separated integers representing the array.
- The third line contains an integer \(x\), the number of top frequent elements to output.
outputFormat
For each test case, output a single line containing \(x\) integers separated by a space. These integers are the \(x\) most frequent elements in the array sorted by descending frequency. If two elements have the same frequency, output the smaller element first.
## sample3
10
1 2 2 3 3 3 4 4 4 4
3
9
8 8 9 9 9 6 6 6 6
2
5
-1000 -1000 1000 1000 0
2
4 3 2
6 9
-1000 1000
</p>