백준/Class3

[백준] Class3-듣보잡 C++ 1764번

taene_ 2023. 9. 12. 10:45

문제

김진영이 듣도 못한 사람의 명단과, 보도 못한 사람의 명단이 주어질 때, 듣도 보도 못한 사람의 명단을 구하는 프로그램을 작성하시오.

 

입력

첫째 줄에 듣도 못한 사람의 수 N, 보도 못한 사람의 수 M이 주어진다. 이어서 둘째 줄부터 N개의 줄에 걸쳐 듣도 못한 사람의 이름과, N+2째 줄부터 보도 못한 사람의 이름이 순서대로 주어진다. 이름은 띄어쓰기 없이 알파벳 소문자로만 이루어지며, 그 길이는 20 이하이다. N, M은 500,000 이하의 자연수이다.

듣도 못한 사람의 명단에는 중복되는 이름이 없으며, 보도 못한 사람의 명단도 마찬가지이다.

출력

듣보잡의 수와 그 명단을 사전순으로 출력한다.

예제 입력 1 복사

3 4
ohhenrie
charlie
baesangwook
obama
baesangwook
ohhenrie
clinton

예제 출력 1 복사

2
baesangwook
ohhenrie

 

소스코드 1:

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
using namespace std;

int N, M;	//듣도, 보도 못한사람
vector<string> result;
map<string, int> k;

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

	cin >> N >> M;

	for (int i = 0; i < N + M; i++)
	{
		string a;
		cin >> a;
		k[a]++;
		if (k[a] > 1)
			result.push_back(a);
	}

	sort(result.begin(), result.end());
	cout << result.size() << '\n';
	for (int i = 0; i < result.size(); i++)
		cout << result[i] << '\n';
}

소스코드 2:

#include <iostream>
#include <map>
using namespace std;

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

	map<string, int> m;
	string s;
	int a, b;
	cin >> a >> b;
	while (a--)
	{
		cin >> s;
		m[s]++;
	}
	while (b--)
	{
		cin >> s;
		m[s]++;
	}
	
	int count = 0;
	for (auto it = m.begin(); it != m.end(); it++)
	{
		if (it->second > 1)
		{
			count++;
		}
	}
	cout << count << '\n';

	for (auto it = m.begin(); it != m.end(); it++)
	{
		if (it->second > 1)
		{
			cout << it->first << '\n';
		}
	}
}

접근방법: map을 사용해서 중복없이 값을 찾아낸다.