알고리즘/백준

백준_1181 : 단어 정렬 - C++

맏리믓 2023. 5. 16. 18:36

문제


알고리즘

- 주어진 string 들을 vector 로 담은 후 조건에 맞게 정렬만 해 주면 되는 문제이다.

- 이때 정렬은 sort 함수를 통해 쉽게 구현 할 수 있다.

- sort 함수에 사용 될 compare 함수는 길이가 같을때는 사전 순으로, 길이가 다를때는 길이 순으로 return 해 준다.

- 중복 단어는 한번만 출력 되므로 정렬 후 중복은 출력 해 주지 않으면 된다.


코드

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

vector<string> input;

bool cmp(string a, string b){
    if(a.length() == b.length()){
        return a < b;
    } else {
        return a.length() < b.length();
    }
}

int main(){
    int N;
    cin >> N;

    for(int i = 0; i < N; i++){
        string tmp;
        cin >> tmp;
        input.push_back(tmp);
    }
    sort(input.begin(), input.end(), cmp);

    
    for(int i = 0; i < N; i++){
        if(i > 0){
            if(!input[i].compare(input[i-1]) == 0){
                cout << input[i] << '\n';    
            }
        } else {
            cout << input[i] << '\n';
        }
    }
    return 0;
}