Algorithm/백준

[백준] 14425 문자열 집합 with C++

nowkoes 2023. 4. 17. 00:00

문제설명


입출력 예제


개념

 이 전의 포스팅된 문제와 유사하게 해결할 수 있는 문제다. M개의 문자열 중에 N개의 문자열과 겹치는 게 있는지 개수를 카운팅 하는 문제다. 이진 탐색을 이용하여 개수를 늘리는 식으로 해결할 수 있다.


풀이

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

int main()
{
	int N, M, count = 0;
	std::string str;
	std::vector<std::string> v;
	std::cin >> N >> M;

 문자열의 개수 N, M과 겹치는 문자열의 개수 count를 초기화한다. 그리고 입력으로 받을 문자열 str과 문자열을 저장할 컨테이너 v를 초기화한다.

 

	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))
			count++;
	}

	std::cout << count;
}

 M개의 문자열을 이진 탐색을 이용하여 count의 개수를 늘려준다.

 

총합본

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

int main()
{
	int N, M, count = 0;
	std::string str;
	std::vector<std::string> v;
	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))
			count++;
	}

	std::cout << count;
}

 

반응형