<< 문제 >>
https://www.acmicpc.net/problem/20920
20920번: 영단어 암기는 괴로워
첫째 줄에는 영어 지문에 나오는 단어의 개수 $N$과 외울 단어의 길이 기준이 되는 $M$이 공백으로 구분되어 주어진다. ($1 \leq N \leq 100\,000$, $1 \leq M \leq 10$) 둘째 줄부터 $N+1$번째 줄까지 외울 단
www.acmicpc.net
map을 활용해서 first에 단어, second에 등장 횟수를 저장합니다.
이렇게 모든 단어를 확인한 후,
map은 이미 순서가 오름차순으로 정렬되어 있기 때문에
vector<pair>로 이동시켜 새로 정렬한다.
이 때, sort()에 새로운 comp 함수를 정의해서 풀이한다.
<< 코드 >>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
bool comp(pair<string, int> p1, pair<string, int> p2){
  // 단어의 출현 수
  if(p1.second != p2.second){
      return p1.second > p2.second;
  }
  
  // 단어 길이
  if(p1.first.size() != p2.first.size()){
      return p1.first.size() > p2.first.size();
  }
  
  // 사전 순
  if(p1.first != p2.first){
      return p1.first < p2.first;
  }
}
int main(){
  ios_base :: sync_with_stdio(false);
  cin.tie(NULL);
  
  int numN, numM;
  cin >> numN >> numM;
  int top = 0;
  map<string, int> wordMap;
  string str;
  for(int i=0; i<numN; i++){
    cin >> str;
    if(str.size() < numM){
      continue;
    }
    
    auto address = wordMap.find(str);
    if(address == wordMap.end()){
      wordMap.insert({str, 1});
    }
    else{
      address->second++;
      if(address->second > top){
        top = address->second;
      }
    }
  }
  
  vector<pair<string,int>> vec;
  for(auto& a : wordMap){
    vec.push_back(a);
  }
  
  sort(vec.begin(), vec.end(), comp);
  
  for(auto& v : vec){
    cout << v.first << '\n';
  }
}
<< 깃헙 >>

| < 백준 BaekJoon : 14889번 스타트와 링크 > C++ (0) | 2024.01.26 | 
|---|---|
| < 백준 BaekJoon : 14888번 연산자 끼워넣기 > C++ (0) | 2024.01.25 | 
| < 백준 BaekJoon : 26069번 붙임성 좋은 총총이 > C++ (0) | 2024.01.24 | 
| < 백준 BaekJoon : 1037번 약수 > C++ (0) | 2024.01.24 | 
| < 백준 BaekJoon : 1037번 약수 > C++ (0) | 2024.01.24 | 
댓글 영역