본문 바로가기
Algorithm/Baekjoon

[백준/BOJ] 1181번 - 단어 정렬 (C++)

by shine-jung 2021. 7. 20.
반응형

문제 링크

 

코딩하기 전 생각하기

/*
중복을 허용하지 않고 정렬하면서 값을 추가할 수 있는 set을 선언하자.
n만큼 단어를 입력받고 set에 추가한다.
set을 출력한다.
*/

 


 

코드

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

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

int main() {
    int n;
    cin >> n;
    set<string, decltype(comp)*> dict(comp);
    string s;
    for ( int i = 0; i < n; i++ ) {
        cin >> s;
        dict.insert(s);
    }
    for ( auto i : dict )
        cout << i << '\n';
}

 


 

느낀점

 

set에 정렬하면서 값을 추가하는 기능을 구현하기 위해 구글링을 했다.

https://stackoverflow.com/questions/2620862/using-custom-stdset-comparator

 

Using custom std::set comparator

I am trying to change the default order of the items in a set of integers to be lexicographic instead of numeric, and I can't get the following to compile with g++: file.cpp: bool lex_compare(const

stackoverflow.com

위 링크의 3번째 솔루션을 참고하였다.

 

(주의) 기록용으로 작성한 글입니다. 코드가 허접하거나 알고리즘의 효율이 낮을 수 있습니다.

댓글 환영합니다!

반응형

댓글