백준 문풀

백준 1764

조강학 2024. 5. 6. 23:53

듣보잡

두 map에서 겹치는 원소를 찾기 위해 추가적으로 result map을 이용하였다.

모든 요소들을 result에 추가하면서 벨류를 증가시켜 겹치는 키의 벨류가 증가하도록 하였다.

interator가 가르키는 요소의 키값이 존재하고 2번 입력받았다면 count를 증가시키고 아니라면 result 에서 원소를 삭제했다.

count로 겹치는 요소의 개수를 출력해주었다.

result에 남은 요소는 겹치는 요소만 남긴 것이기 때문에 result의 요소를 모두 출력해줘 프로그램을 완성했다.

 

#include <iostream>
#include <map>
#include <string>

using namespace std;

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

    map<string, int> see;
    map<string, int> hear;
    map<string, int> result;

    int n, m, count = 0;
    string str;

    cin >> n >> m;

    for (int i = 0; i < n; i++) {
        cin >> str;
        hear[str]++;
        result[str]++;
    }

    for (int j = 0; j < m; j++) {
        cin >> str;
        see[str]++;
        if (result.find(str) != result.end()) {
            result[str]++;
        }
        else {
            result[str]++;
        }
    }

    for (auto it = result.begin(); it != result.end();) {
        if (hear[it->first] > 0 && see[it->first] > 0) {
            count++;
            ++it;
        }
        else {
            it = result.erase(it);
        }
    }

    cout << count << "\n";
    for (auto it = result.begin(); it != result.end(); ++it) {
        cout << it->first << "\n";
    }

    return 0;
}

'백준 문풀' 카테고리의 다른 글

백준 11866  (0) 2024.05.08
백준 2840  (0) 2024.05.08
백준 11478  (0) 2024.05.06
백준 11279  (0) 2024.05.06
백준 7785  (0) 2024.05.06