백준 문자열 집합 14425 C++

Jaedup·2023년 3월 19일
0

알고리즘 문제풀이

목록 보기
5/10

집합 S에 포함되는 문자열의 개수를 세는 문제.
테스트 케이스가 많아서 일반적인 비교로는 풀 수 없다.

c의 stdio와 c++의 iostream 간의 동기화를 끊어주고, cin과 cout의 묶음을 풀어주는 방식으로는 역부족이다.

ios_base::sync_with_stdio(false);
cin.tie(NULL);

따라서 시간 초과를 해결하기 위해 레드 블랙 트리로 이루어진 map STL을 이용하면 된다.
map의 탐색연산 시간 복잡도는 O(log N)이다.

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

int main() {

	//ios_base::sync_with_stdio(false);
	//cin.tie(NULL);

	int n, m;
	int cnt = 0;
	cin >> n >> m;
	
	map<string, bool> word_map;

	string tmp;
	for (int i = 0; i < n; i++) {
		cin >> tmp;
		word_map[tmp] = true;
	}

	for (int i = 0; i < m; i++) {
		cin >> tmp;
		
		if (word_map[tmp]) {
			cnt++;
		}
	}
	cout << cnt;
}

0개의 댓글