백준 1181 단어 정렬
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool compare(string a, string b) {
if (a.size() < b.size()) return true;
else if (a.size() == b.size())
return a < b;
else return false;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
string words[20001];
int n;
cin >> n;
for (int i = 0; i < n; ++i)
cin >> words[i];
sort(words, words + n, compare);
for (int i = 0; i < n; ++i) {
cout << words[i]<<"\n";
while (i < n) {
if (words[i] == words[i + 1]) ++i;
else break;
}
}
return 0;
}
다른 풀이
#include <algorithm>
#include <vector>
#include <string>
#include <set>
#include <iostream>
using namespace std;
bool cmp(string a, string b) {
if (a.length() < b.length()) return true;
else if (a.length() == b.length()) return a < b;
return false;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int n;
cin >> n;
set<string> s;
for (int i = 0; i < n; ++i) {
string str;
cin >> str;
s.insert(str);
}
vector<string> vec(s.begin(), s.end());
sort(vec.begin(), vec.end(), cmp);
for (int i = 0; i < vec.size(); ++i) {
cout << vec[i] << "\n";
}
return 0;
}