관리 메뉴

Mini

백준 2910 빈도정렬 // 커스텀정렬, 인덱스에 의미부여 본문

Algorithm/boj

백준 2910 빈도정렬 // 커스텀정렬, 인덱스에 의미부여

Mini_96 2023. 5. 3. 15:30

2910번: 빈도 정렬 (acmicpc.net)

 

2910번: 빈도 정렬

첫째 줄에 메시지의 길이 N과 C가 주어진다. (1 ≤ N ≤ 1,000, 1 ≤ C ≤ 1,000,000,000) 둘째 줄에 메시지 수열이 주어진다.

www.acmicpc.net

* 인덱스에 의미를 부여하라!

ex)mp[2] ==2의 빈도

 

mp(해당숫자,빈도)

mp_first(해당숫자,최초등장순서)

v(빈도,해당숫자)

 

*빈도수(v.first)만큼 출력해야함에 주의

ex) (0,0) (2,1) (3,2) 일때, 0은 출력안됨, 1 1 2 2 2 출력.

for (auto i : v) {
        for (int j = 0; j < i.first; j++) 
        {
            //빈도수만큼 출력해야함!!
            cout << i.second << " ";
        }
    }
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
int n, c, a[1004];
map<int, int> mp,mp_first;  //빈도저장,등장순서저장
vector<pair<int, int>> v;   //<빈도,key>

bool cmp(pair<int, int> a, pair<int, int> b)
{
    if (a.first == b.first)
        return mp_first[a.second] < mp_first[b.second];
    return a.first > b.first;
}

int main() {
    ios_base::sync_with_stdio(0); 
    cin.tie(NULL); cout.tie(NULL);
    cin >> n>>c;

    for (int i = 0; i < n; ++i)
    {
        cin >> a[i];
        mp[a[i]]++; //인덱스==키, 값==해당키의 빈도수
        if (mp_first[a[i]] == 0) mp_first[a[i]] = i+1;
        //첫등장이면, 등장순서 저장

       // v.push_back({ mp[a[i]] ,a[i] });
    }
    for (auto it : mp) {
        v.push_back({ it.second, it.first });
    }
    sort(v.begin(), v.end(), cmp);
    for (auto i : v) {
        for (int j = 0; j < i.first; j++) 
        {
            //빈도수만큼 출력해야함!!
            cout << i.second << " ";
        }
    }
    
    
    return 0;
}