[백준(BOJ)] 영단어 암기는 괴로워(20920번)_C++
2024. 3. 25. 13:54ㆍProblem Solving/Sort
728x90
반응형
SMALL
문제에서 주어진 기준에 맞게 정렬하는 문제다.
다만 주어진 조건이 일반적인 크기비교가 아닌 다소 복잡한 조건이다.
따라서 이에 맞게 compare 함수를 정의해야 한다.
나는 map을 사용해 각 단어에 대한 횟수를 저장하고
이를 활용해 vector에 정렬하여 저장했다.
정답 코드
#include <iostream>
#include <map>
#include <algorithm>
#include <vector>
using namespace std;
int n, m;
map<string, int> word;
vector<string> v;
bool cmp(string a, string b){
if (a.length() == b.length() && word[a] == word[b]) {
return a < b;
}
else if (word[a] == word[b]) {
return a.length() > b.length();
}
return word[a] > word[b];
}
int main(){
cin.tie(NULL);
cout.tie(NULL);
ios_base::sync_with_stdio(false);
//input
cin >> n >> m;
for (int i = 0; i < n; i++){
string s;
cin >> s;
if (s.length() < m)
continue;
if (word.find(s) == word.end()){
word.insert({s, 1});
v.push_back(s);
}
else
word[s]++;
}
//sort
sort(v.begin(), v.end(), cmp);
//output
for (int i = 0; i < v.size(); i++)
cout << v[i] << "\n";
}728x90
반응형
LIST
'Problem Solving > Sort' 카테고리의 다른 글
| [백준(BOJ)] 좌표 압축(18870번)_C++ (0) | 2023.04.01 |
|---|---|
| [백준(BOJ)] 철로(13334번)_C++ (0) | 2023.03.28 |
| 백준(BOJ)_줄 세우기(2252번)_C++ (0) | 2022.08.28 |
| 백준(BOJ)_듣보잡(1764번)_C++ (0) | 2022.08.18 |
| 백준(BOJ)_전화번호 목록(5052번)_C++ (0) | 2022.08.17 |