Pokeball - Pokemon

99클럽 TIL

99클럽 코테 스터디 31일차 TIL + 문자열&정렬(C++)

ansi. 2024. 11. 28. 00:45

문제

[백준] 1755번: 숫자놀이

https://www.acmicpc.net/problem/1755

 

코드

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

int main() {
    // 0~9 숫자와 해당 영어 발음을 매칭하는 벡터
    vector<string> words = { "zero", "one", "two", "three", "four", 
                            "five", "six", "seven", "eight", "nine" };

    int M, N;   // M: 범위의 시작, N: 끝
    cin >> M >> N;

    // 숫자의 영어 발음과 원래 숫자를 저장할 벡터
    vector<pair<string, int>> ans;

    for (int i = M; i <= N; i++) {
        string str = "";    // 숫자의 영어 발음을 저장할 문자열
        int num = i;

        // 숫자의 각 자릿수를 영어 발음으로 변환하여 str에 추가
        while (num > 0) {
            int tmp = num % 10;
            str = words[tmp] + str;
            num /= 10;
        }

        // 변환한 영어 발음과 원래 숫자를 pair로 저장
        ans.push_back( {str, i} );
    }

    // 영어 발음을 기준으로 ans 벡터를 사전순 정렬
    sort(ans.begin(), ans.end());

    for (int i = 0; i < ans.size(); i++) {
        // 10개씩 출력 후 줄바꿈
        if (i != 0 && i % 10 == 0)
            cout << '\n';

        // 정렬된 영어 발음 순서대로 해당 숫자 출력
        cout << ans[i].second << ' ';
    }

    return 0;
}

 

풀이

주석으로 대체합니다.

 

🔎 pair를 자료형으로 가지는 벡터를 오름차순 정렬

pair를 자료형으로 가지는 벡터를 sort로 오름차순 정렬할 때는,

  • 기본적으로 pair첫 번째 요소(first)를 기준으로 정렬한다.
  • 만약 첫 번째 요소가 같다면 두 번째 요소(second)를 기준으로 정렬한다.