백준 algorithm

백준 1302 베스트셀러 C++

cosmohoo 2022. 7. 18. 23:35
반응형

문제설명

 

출력

첫째 줄에 가장 많이 팔린 책의 제목을 출력한다. 만약 가장 많이 팔린 책이 여러 개일 경우에는 사전 순으로 가장 앞서는 제목을 출력한다.

예제 입력 1 복사

5
top
top
top
top
kimtop

예제 출력 1 복사

top

예제 입력 2 복사

9
table
chair
table
table
lamp
door
lamp
table
chair

예제 출력 2 복사

table

예제 입력 3 복사

6
a
a
a
b
b
b

예제 출력 3 복사

a

 

 

=> MAP 자료구조에 대해 아는지 묻는 문제였습니다. 

=> MAP 자료구조를 통해 가장 많이 나온 단어의 횟수를 저장합니다. 

=> 가장 많이 나온 단어의 횟수를 VALUE로 갖고 있는 영단어들을 VECTOR에 삽입합니다. 

=> 해당 VECTOR를 알파벳순으로 정렬합니다. 

 

#include <string>
#include <algorithm>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <iostream>
#include <queue>
#include <utility>
#include <stdio.h>
#include <map>
using namespace std;



int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    //KEY 단어 , VALUE 나온횟수
    map<string,int> bestS;
    int N;
    cin >> N;
    
    while(N>0)
    {
        //MAP에 객체 삽입
        string tmp;
        cin >> tmp;
        bestS[tmp]++;
        
        N--;
    }
    
    int maxV=0;
    //최대 많이 나온 횟수 추출
    for(auto iter : bestS)
    {
        maxV = max(maxV, iter.second);
    }
    
    //답안추출위한 vector선언
    vector<string> answer;
    //최대 많이 나온 단어 추출하여 vector에 삽입
    for(auto iter : bestS)
    {
        if(iter.second == maxV)
        {
            answer.push_back(iter.first);
        }
    }
    
    //vector정렬(사전순)
    sort(answer.begin(),answer.end());
    
    cout << answer[0];
}

반응형