[백준 20920] 영단어 암기는 괴로워

alsry._.112·2023년 10월 23일
0

백준

목록 보기
92/102

🔗문제 풀러가기
단계별로 풀어보기 단계 20의 4번째 문제이다.

문제 분석

map과 vector, sort함수를 활용하여 문제를 해결하였다.

코드

#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;

bool compare(pair<string, int> p1, pair<string, int> p2)
{
    if (p1.second == p2.second)
    {
        if (p1.first.size() == p2.first.size())
        {
            return p1.first < p2.first;
        }
        return p1.first.size() > p2.first.size();
    }
    return p1.second > p2.second;
}

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

    int n, m;
    cin >> n >> m;

    string input;
    map<string, int> _map;

    for (int i = 0; i < n; i++)
    {
        cin >> input;
        if (input.size() >= m)
        {
            _map[input]++;
        }
    }

    vector<pair<string, int>> sortedMap(_map.begin(), _map.end());
    sort(sortedMap.begin(), sortedMap.end(), compare);

    for (const auto& a : sortedMap)
    {
        cout << a.first << "\n";
    }
}

해석

  1. 입력받은 n만큼 string을 입력받는다.
  2. 입력받은 string의 길이가 m보다 길다면 맵에서 입력받은 string 인덱스의 값을 ++한다.
  3. map은 자동으로 정렬이 되므로 정렬이 되지 않는 vector를 선언하여 map의 begin부터 end까지의 값으로 초기화 해준다.
  4. 그후 주어진 조건에 맞게 작성한 compare함수를 마지막 인자로 넣은 sort함수를 통해 정렬을 하고 전부 출력해주면 끝!
profile
소통해요

0개의 댓글