문제해결방법
1. for문을 통해 입력을 받는 동시에 길이가 M미만인 단어는 거른고 M이상인 단어만 HashMap에 insert 한다.
2. hashMap은 순서가 없기 때문에 hashMap 있는 데이터를 vector에 옮긴다.
3. vector를 정렬하는데 비교함수를 정의해서 정렬한다.
4. 백터의 요소를 출력한다.
#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(pair<string, int>& a, pair<string, int>& b)
{
if (a.second == b.second)
{
if (a.first.length() == b.first.length())
{
return a.first < b.first;
}
else
{
return a.first.length() > b.first.length();
}
}
else
{
return a.second > b.second;//여기서 return은 bool값이다. 만약 a.second가 5고 b.second가 3이면 5>3 true가 반환된다.
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
unordered_map<string,int> hashMap;
int N = 0;
int M = 0;
cin >> N >> M;
for (int i = 0; i < N; i++)
{
string temp = "";
cin >> temp;
if (temp.length() >= M)
{
hashMap[temp]++;
}
}
vector <pair<string, int>> V(hashMap.begin(), hashMap.end());
sort(V.begin(), V.end(), cmp);
for (auto p : V)
{
cout << p.first << "\n";
}
}
이 문제를 통해 비교함수를 정의하는 방법을 알게 되었고, hashMap의 요소를 백터로 복사하는 방법도 알게 되었다.
'백준 > 해시' 카테고리의 다른 글
[백준] C++ 2002번 추월 (0) | 2024.09.29 |
---|---|
[백준] C++ 4358번 생태학 (0) | 2024.09.29 |
[백준] C++ 11478번 서로 다른 부분 문자열의 개수 (1) | 2024.09.28 |
[백준] C++ 14425 문자열 집합 (0) | 2024.09.25 |
[백준] C++1764 듣보잡 (2) | 2024.09.25 |