Home BOJ - 1181 - 단어정렬
Post
Cancel

BOJ - 1181 - 단어정렬

BOJ - 1181 - 단어정렬

문제


https://user-images.githubusercontent.com/71277820/161379931-88db8595-a80c-42d5-85ae-4e460919175b.png

SOL


  • 문자열의 길이순으로 정렬 후 사전순으로 정렬
    • sort의 compare를 사용하여 조건문을 만들어 줌.

      1
      2
      3
      4
      5
      6
      
        bool compare(string a, string b)
        {
            if(a.size() == b.size())
                return a < b;
            return a.size() < b.size(); 
        }
      
  • 중복 제거

    st_list.erase(unique(st_list.begin(), st_list.end()), st_list.end());

정답 소스


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

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

int main()
{
    int num;
    string str;
    vector<string> st_list;
    scanf("%d", &num);
    for(int i=0; i < num; i++)
    {
        cin >> str;
        st_list.push_back(str);
    }
    sort(st_list.begin(), st_list.end(), compare);
    st_list.erase(unique(st_list.begin(), st_list.end()), st_list.end());
    for(int i=0; i < st_list.size(); i++)
        cout << st_list[i] << endl;
}

출력


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
13
but
i
wont
hesitate
no
more
no
more
it
cannot
wait
im
yours
------------
i
im
it
no
but
more
wait
wont
yours
cannot
hesitate

Reference & 다른 PS 모음집


C++ STL sort ( )

https://github.com/ggh-png/PS

This post is licensed under CC BY 4.0 by the author.