알고리즘 풀이
단어 정렬
남생이야
2024. 8. 10. 03:48
https://www.acmicpc.net/problem/1181
map을 사용했다. map은 키값을 오름차순 정렬으로 처리되기 때문에 채택했으며 길이가 같더라도 그대로 출력하면 그만이였다. 다만 이제 길이가 짧은 경우를 생각해야 했기 때문에 map 자체적으론 sort 함수를 사용할 수 없다. 그러므로 vector에 그대로 값을 넣어서 campare함수를 구현해야 했다.
길이가 같은 경우 그냥 true를 반환하려는데 이것이 에러를 표출해내었는데 이는 내부적으로 문제를 야기한다. 첫 번째로 어떤 순서로 둘지를 결정하는 것인데 이미 a가 b앞인 경우라면 true가 아닌 false가 와야한다..true 할 경우 내부적으로 위배되는 알고리즘을 반환하기 때문에 에러가 난 것..
#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
using namespace std;
bool comapare(pair<string, int>& a, pair<string, int>& b)
{
if (a.second == b.second)
return a.first < b.first;
return a.second < b.second;
}
int main()
{
int n;
cin >> n;
map<string, int> wordMap;
for (int i = 0; i < n; i++)
{
string str;
cin >> str;
if (wordMap.find(str) == wordMap.end())
{
wordMap.insert({ str, str.size() });
}
}
vector<pair<string, int>> results(wordMap.begin(), wordMap.end());
sort(results.begin(), results.end(), comapare);
for (int i = 0; i < results.size(); i++)
{
cout << results[i].first << endl;
}
return 0;
}