알파벳 소문자로 이루어진 N개의 단어가 들어오면 아래와 같은 조건에 따라 정렬하는 프로그램을 작성하시오.
1. 길이가 짧은 것부터
2. 길이가 같으면 사전순으로
첫째 줄에 단어의 개수 N이 주어진다.(1<=N<=20000)
둘째 줄 부터 N개의 줄에 걸처 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.
조건에 따라 정렬하여 단어들을 출력한다. 단, 같은 단어가 여러번 입력된 경우에는 한 번씩만 출력한다.
vector에 주어진 string을 받아, second요소로 길이를 저장하여 문제를 해결하였다. sort 함수의 3번째 파라미터를 사용하기 위해 compare 함수를 이용하여 문자열의 길이가 같은 경우, 사전순으로 정렬하도록 하였다.
또한, 중복되는 문자열은 저장하지 않도록 하였다.
#include <iostream>
#include <vector>
#include<algorithm>
#include<string>
#include<cstring>
using namespace std;
bool compare(const pair<string, int> &a, pair<string, int> &b) {
if (a.second == b.second)
return a.first<b.first;
else
return a.second<b.second;
}
int main() {
int n;
vector<pair<string, int>> words;
cin >> n;
for (int i = 0; i < n; i++) {
string word;
int length;
cin >> word;
length = word.size();
words.push_back(make_pair(word, length));
//중복 제거
for (int j = 0; j < words.size()-1; j++) {
if (words[j].first == word) {
words.pop_back(); break;
}
}
}
sort(words.begin(), words.end(),compare);
for (int i = 0; i < words.size(); i++)
cout << words[i].first << '\n';
return 0;
}