[C++] 백준 1181번 단어 정렬

xyzw·2025년 2월 7일
0

algorithm

목록 보기
16/61

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

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

bool comp(string a, string b){
    if(a.size() == b.size()) {
        return a < b;
    }
    return a.size() < b.size();
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);
    
    int n;
    string input;
    set<string> s;
    vector<string> v;
    
    cin >> n;
    
    while(n--){
        cin >> input;
        s.insert(input);
    }
    
    for(auto& e : s){
        v.push_back(e);
    }
    
    sort(v.begin(), v.end(), comp);
    
    for(auto& e : v) {
        cout << e << "\n";
    }
    
    return 0;
}

풀이

중복 없이 단어를 입력받을 수 있도록 set을 사용하였다. set의 요소들을 vector에 옮기고 comp 함수로 기준을 적용하여 정렬하였다.


set의 정렬 기준을 바꾸는 방법이 있었다.
https://chanhuiseok.github.io/posts/algo-46/

0개의 댓글