문제

알고리즘
- 주어진 string 들을 vector 로 담은 후 조건에 맞게 정렬만 해 주면 되는 문제이다.
- 이때 정렬은 sort 함수를 통해 쉽게 구현 할 수 있다.
- sort 함수에 사용 될 compare 함수는 길이가 같을때는 사전 순으로, 길이가 다를때는 길이 순으로 return 해 준다.
- 중복 단어는 한번만 출력 되므로 정렬 후 중복은 출력 해 주지 않으면 된다.
코드
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<string> input;
bool cmp(string a, string b){
if(a.length() == b.length()){
return a < b;
} else {
return a.length() < b.length();
}
}
int main(){
int N;
cin >> N;
for(int i = 0; i < N; i++){
string tmp;
cin >> tmp;
input.push_back(tmp);
}
sort(input.begin(), input.end(), cmp);
for(int i = 0; i < N; i++){
if(i > 0){
if(!input[i].compare(input[i-1]) == 0){
cout << input[i] << '\n';
}
} else {
cout << input[i] << '\n';
}
}
return 0;
}
'알고리즘 > 백준' 카테고리의 다른 글
백준_1074 : Z - C++ (0) | 2023.05.16 |
---|---|
백준_1259 : 팰린드롬수 - C++ (0) | 2023.05.16 |
백준_1012 : 유기농 배추 - C++ (1) | 2023.05.10 |
백준_1003 : 피보나치 함수 - C++ (1) | 2023.05.10 |
백준_1085 : 직사각형에서 탈출 - C++ (0) | 2023.05.10 |