std::string, std::vector 사용.
중복되는 요소는 std::unique 함수로 배제.
#include<iostream>
#include<algorithm>
#include<vector>
#include<cstdio>
using namespace std;
bool compare(const string &s1, const string &s2) {
if (s1.size() == s2.size()) return s1 < s2;
else return s1.size() < s2.size();
}
int N;
char word[51];
vector<string> dict;
int main(void) {
scanf("%d", &N);
for (int i = 0; i < N; i++) {
scanf("%s", word);
dict.push_back((string)word);
}
vector<string>::iterator iter;
vector<string>::iterator end_iter;
sort(dict.begin(), dict.end(), compare);
end_iter = unique(dict.begin(), dict.end());
for (iter = dict.begin(); iter != end_iter; iter++) {
printf("%s\n", (*iter).c_str());
}
return 0;
}
저수준 데이터 입출력 사용
string 대신 char[50], vector 대신 array.
#include <iostream>
#include <cstring>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
// fast_io 라이브러리 생략.
struct word {
char data[51];
};
bool compare(const word& s1, const word& s2){
auto len_s1 = strlen(s1.data);
auto len_s2 = strlen(s2.data);
if(len_s1 != len_s2) return len_s1 < len_s2;
return 0 > strcmp(s1.data, s2.data);
}
bool isEquals(const word &s1, const word &s2){
for(auto i=0; i<=50; i++){
if(s1.data[i] != s2.data[i]) return false;
if(s1.data[i] == 0) return true;
}
return true;
}
int main() {
int N;
int_io(READ, N);
word arr[N];
memset(arr, 0, sizeof arr);
for(int i=0; i<N; i++){
word_io(READ, arr[i].data);
}
sort(arr, arr+N, compare);
auto end = unique(arr, arr + N, isEquals) - arr;
for(int i=0; i<end; i++){
word_io(WRITE, arr[i].data);
char_io(WRITE, '\n');
}
char_io(WRITE, EOF);
}