C - (K+1)-th Largest Number Editorial by en_translator
We first find what integer occurs how many times in \(A\). Specifically, we find a sequence \(((v_1, f_1), (v_2, f_2), (v_3, f_3), \ldots, (v_n, f_n))\) such that
- integer \(v_i\) occurs \(f_i\) times in \(A\);
- \(v_1 \gt v_2 \gt \cdots \gt v_n \gt 0\); and
- \(\sum_{i = 1}^n f_i = N\).
For example, if \(A = (100, 200, 200, 100, 300, 100)\), if contains three \(100\)’s, two \(200\)’s, and one \(300\)’s, so \(((v_1, f_1), (v_2, f_2), (v_3, f_3)) = ((300, 1), (200, 2), (100, 3))\).
In order to obtain \(((v_1, f_1), (v_2, f_2), (v_3, f_3), \ldots, (v_n, f_n))\), we need to find what integers occurs how many times in \(A\) and sort them in descending order; it can be achieved with an associative array.
For each \(i = 1, 2, \ldots, n\), there are \(i-1\) distinct integers, \(v_1, v_2, \ldots, v_{i-1}\), that is greater than \(v_i\), so for each \(K = 0, 1, 2, \ldots, n-1\), the answer for \(K\) is \(f_{K+1}\), and for \(K = n, n+1, \ldots, N-1\), the answer is \(0\).
To summarize, in order to get accepted for this problem, we first find \(((v_1, f_1), (v_2, f_2), (v_3, f_3), \ldots, (v_n, f_n))\) with an associative array, print \(f_1, f_2, \ldots, f_n\) in this order, and then print \((N-n)\) zeros.
The following is a sample code in C++.
#include <iostream>
#include <map>
using namespace std;
int main(void)
{
int n, a;
map<int, int> mp;
cin >> n;
for(int i = 1; i <= n; i++) cin >> a, mp[a]++;
for(auto it = mp.rbegin(); it != mp.rend(); it++) cout << it->second << "\n";
for(int i = 1; i <= n - (int)mp.size(); i++) cout << 0 << "\n";
return 0;
}
posted:
last update: