[백준(BOJ)] 영단어 암기는 괴로워(20920번)_C++

2024. 3. 25. 13:54Problem Solving/Sort

728x90
반응형
SMALL

문제에서 주어진 기준에 맞게 정렬하는 문제다.

다만 주어진 조건이 일반적인 크기비교가 아닌 다소 복잡한 조건이다.

따라서 이에 맞게 compare 함수를 정의해야 한다.

 

나는 map을 사용해 각 단어에 대한 횟수를 저장하고

이를 활용해 vector에 정렬하여 저장했다.

 


정답 코드

#include <iostream>
#include <map>
#include <algorithm>
#include <vector>

using namespace std;

int n, m;
map<string, int> word;
vector<string> v;

bool cmp(string a, string b){
    if (a.length() == b.length() && word[a] == word[b]) {
        return a < b;
    }
    else if (word[a] == word[b]) {
        return a.length() > b.length();
    }
    return word[a] > word[b];
}

int main(){
    cin.tie(NULL);
    cout.tie(NULL);
    ios_base::sync_with_stdio(false);

    //input
    cin >> n >> m;
    for (int i = 0; i < n; i++){
        string s;
        cin >> s;

        if (s.length() < m)
            continue;
        
        if (word.find(s) == word.end()){
            word.insert({s, 1});
            v.push_back(s);
        }
        else
            word[s]++;
    }

    //sort
    sort(v.begin(), v.end(), cmp);

    //output
    for (int i = 0; i < v.size(); i++)
        cout << v[i] << "\n";
}
728x90
반응형
LIST