https://www.acmicpc.net/problem/1181
중복된 단어를 제거해야 하기 때문에 집합 자료형인 set을 사용하고 set를 vector로 변환해서 다시 정렬함수를 적용하면 된다.
정렬함수에서는 길이로 먼저 비교하고 사전순은 string 자체를 비교하면 된다.
정답코드
#include "iostream"
#include "vector"
#include "set"
#include "algorithm"
using namespace std;
// 정렬 기준 함수
bool cmp(const string& a, const string& b) {
if (a.length() == b.length()) {
return a < b; // 길이가 같으면 사전순 정렬
}
return a.length() < b.length(); // 길이가 다르면 짧은 순으로 정렬
}
int main()
{
int n;
cin >> n;
set<string> s;
for (int i = 0; i < n; i++)
{
string word;
cin >> word;
s.insert(word);
}
//set -> vector
vector<string> v(s.begin(), s.end());
sort(v.begin(), v.end(),cmp);
for (int i = 0; i < v.size(); i++)
{
cout << v[i] << endl;
}
return 0;
}
'코딩테스트 > 백준' 카테고리의 다른 글
[백준][C++]18870번. 좌표 압축 (0) | 2024.09.24 |
---|---|
[백준][C++]10814번. 나이순 정렬 (2) | 2024.09.23 |
[백준][C++]11651번. 좌표 정렬하기 2 (0) | 2024.09.20 |
[백준][C++]11650번. 좌표 정렬하기 (0) | 2024.09.19 |
[백준][C++]1193번. 분수찾기 (2) | 2024.09.18 |