enginner_s2eojeong

C++ [baekjoon] 1181번: 단어 정렬 본문

Algorithm/Baekjoon

C++ [baekjoon] 1181번: 단어 정렬

_danchu 2024. 5. 3. 23:33

백준 1181번

 

[코드]

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

int compare(string a, string b){ 
    if (a.length() == b.length()) return a<b; // 길이가 같다면 알파벳 순
    else return a.length()<b.length(); // 그게 아니라면 짧은 것 부터
}

int main(){
    int N;
    string word[20000];
    cin >> N;
    for(int i=0; i<N; i++){
        cin >> word[i];
    }
    sort(word, word+N, compare);
    for(int i=0; i<N; i++){
        if (word[i]==word[i+1]) continue; // 중복 되는건 한번만 출력
        cout << word[i] << endl;
    }
    return 0;
}

 

[해설]

c++ 내장함수인 sort를 이용하되 길이가 같은 경우에는 알파벳 순으로, 그 외의 경우에는 길이가 짧은 단어부터 출력되게끔 

compare 함수에 추가 기능을 구현하였다. 

그렇게 문제 조건에 맞게 단어들을 배열을 해놓은 뒤 for 문에서 순서대로 하나하나 출력을 할 때, 같은 단어가 중복되는 경우에는 continue를 사용하여 중복 출력이 되지 않도록 하였다.

 

출처: https://www.acmicpc.net/problem/1181