백준(BOJ)_듣보잡(1764번)_C++

2022. 8. 18. 11:32Problem Solving/Sort

728x90
반응형
SMALL

map이라는 자료구조만 사용할 줄 알면 어렵지 않은 문제였다.

<string, int>를 이용해 사람이름과 빈도 수를 사상시켰다.

 

일반적인 배열만 이용해도 풀 수 있을 것 같다.

하지만 확실히 여러가지 자료구조를 익히고, 상황에 맞게 사용할 줄 아는 것도 중요하다고 생각한다.

 

먼저 듣도 못한 사람의 입력을 map으로 받는다.

듣도 못한 사람의 입력을 받을 때는 중복되는 사람이 없으므로 조건없이 map에 삽입하기만 하면 된다.

 

그리고 보도 못한 사람의 입력을 받을 때는 중복되는 사람이 있을 수 있으므로 조건에 맞게 삽입한다.

 

입력을 모두 받은 후에 map에 있는 문자열 중 그 빈도가 2인 경우에만 따로 벡터에 저장한다.

 

이제 벡터를 정렬한 후, 벡터의 크기와 벡터의 내용을 출력하면 끝이다.

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <map>

using namespace std;

int n, m;
map<string, int> man;
vector<string> answer;

int main() {
    cin.tie(NULL);
    cout.tie(NULL);
    ios_base::sync_with_stdio(false);

    cin >> n >> m;
    for(int i=0; i<n; i++){
        string s;
        cin >> s;
        man.insert({s, 1});
    }
    for(int i=0; i<m; i++){
        string s;
        cin >> s;
        if(man.find(s)==man.end()) man.insert({s, 1});
        else man[s]++;
    }
    for(auto i=man.begin(); i!=man.end(); i++)
        if(i->second==2) answer.push_back(i->first);
    
    sort(answer.begin(), answer.end());
    cout << answer.size() << "\n";
    for(int i=0; i<answer.size(); i++)
        cout << answer[i] << "\n";
}
728x90
반응형
LIST