Algorithm/백준

[백준] 1764 듣보잡 with C++

nowkoes 2023. 4. 20. 00:00

문제설명


입출력 예제


개념

 N개의 문자열과 M개의 문자열 중 겹치는 문자열을 출력하는 문제다. 여기서 사전순으로 출력해야 하기 때문에 set 자료 구조를 이용하여 저장과 동시에 정렬을 하면 편하게 해결할 수 있다.


풀이

#include <iostream>
#include <vector>
#include <set>
#include <algorithm>

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

	int N, M;
	std::string str;
	std::vector<std::string> v;
	std::set<std::string> res;

 문자열의 수 N, M, 입력받을 문자열 str, 초기에 N개의 벡터를 저장할 벡터 v, 최종 적으로 자료를 담을 res를 초기화한다.

 

	std::cin >> N >> M;
	while (N--)
	{
		std::cin >> str;
		v.push_back(str);
	}

	std::sort(v.begin(), v.end());

 N개의 데이터를 벡터에 저장하고 정렬해 준다.

 

	while (M--)
	{
		std::cin >> str;
		if (std::binary_search(v.begin(), v.end(), str))
			res.insert(str);
	}

 M개의 데이터를 입력받는데, 만약 벡터에 존재한다면 res에 데이터를 넣어준다.

 

	std::cout << res.size() << '\n';
	for (auto& val : res)
		std::cout << val << '\n';
}

 res의 크기와 모든 값을 출력해 주면 해결할 수 있다.

 

총합본

#include <iostream>
#include <vector>
#include <set>
#include <algorithm>

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

	int N, M;
	std::string str;
	std::vector<std::string> v;
	std::set<std::string> res;

	std::cin >> N >> M;
	while (N--)
	{
		std::cin >> str;
		v.push_back(str);
	}

	std::sort(v.begin(), v.end());

	while (M--)
	{
		std::cin >> str;
		if (std::binary_search(v.begin(), v.end(), str))
			res.insert(str);
	}

	std::cout << res.size() << '\n';
	for (auto& val : res)
		std::cout << val << '\n';
}

 

반응형