알파벳 소문자로 이루어진 N개의 단어가 들어오면 아래와 같은 조건에 따라 정렬하는 프로그램을 작성하시오.
첫째 줄에 단어의 개수 N이 주어진다. (1 ≤ N ≤ 20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.
조건에 따라 정렬하여 단어들을 출력한다. 단, 같은 단어가 여러 번 입력된 경우에는 한 번씩만 출력한다.
#include <iostream>
#include <string.h>
#include <algorithm>
#include <utility>
#include <cmath>
#include <cstdlib>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
int N;
scanf("%d", &N);
string fake[N], tmp;
int min, len;
for(int i=0;i<N;i++) {
cin >> fake[i];
}
string str[N];
int cnt=0;
for(int i=0;i<N;i++) {
int f =0 ;
for(int j =0;j<cnt;j++) {
if(fake[i] == str[j]) {
f=1;
break;
}
}
if(f==0) {
str[cnt++] = fake[i];
}
}
for(int i=0;i<N;i++) {
for(int j=0;j<N-1;j++) {
if(str[j].length() > str[j+1].length()) {
tmp = str[j];
str[j] = str[j+1];
str[j+1] = tmp;
}
else if(str[j].length() == str[j+1].length() && str[j] > str[j+1]) {
tmp = str[j];
str[j] = str[j+1];
str[j+1] = tmp;
}
}
}
for(int i =0; i<N;i++) {
cout << str[i] << endl;
}
return 0;
}
#include <iostream>
#include <string.h>
#include <algorithm>
#include <utility>
#include <cmath>
#include <cstdlib>
using namespace std;
int cmp(string x, string y);
string str[20000];
int main() {
int N;
cin >> N;
for(int i=0;i<N;i++) {
cin >> str[i];
}
sort(str, str+N, cmp);
for(int i=0;i<N;i++) {
if(str[i] == str[i-1]) {
continue;
}
cout << str[i] << endl;
}
return 0;
}
int cmp(string x, string y){
// 1. 길이가 같다면 사전순으로!
if(x.length() == y.length()) {
return x < y;
}
else {// 2. 길이가 다르다면, 짧은 순으로!
return x.length() < y.length();
}
}