Untitled

mail@pastecode.io avatar
unknown
c_cpp
6 months ago
1.1 kB
2
Indexable
Never
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>

using namespace std;

bool sortByVal(const pair<int, pair<int, int>>& a, const pair<int, pair<int, int>>& b) {
    if(a.second.first == b.second.first) {
        return a.second.second < b.second.second;
    }
    return a.second.first > b.second.first;
}

int main() {
    int num;
    cin >> num;
    vector<int> arr(num);
    unordered_map<int, pair<int, int>> frequencyMap; // <element, <frequency, first_index>>

    for(int i = 0; i < num; ++i) {
        cin >> arr[i];
        if(frequencyMap.find(arr[i]) == frequencyMap.end()) {
            frequencyMap[arr[i]] = make_pair(1, i);
        } else {
            frequencyMap[arr[i]].first++;
        }
    }

    vector<pair<int, pair<int, int>>> freqList(frequencyMap.begin(), frequencyMap.end());

    sort(freqList.begin(), freqList.end(), sortByVal);

    for(const auto& item: freqList) {
        for(int j = 0; j < item.second.first; ++j) {
            cout << item.first << " ";
        }
    }
    cout << endl;
    return 0;
}