🍞 Problem Solving/Baekjoon

[백준] 14425 문자열 집합 c++

박빵이 2022. 9. 13. 23:52

풀이과정

처음에는 단순히 배열에 값을 넣어서 있으면 cnt하는 반복문을 돌렸었다.  
그러나 실버3은 역시 간단할리 없었다.

map에 string 값을 key로 넣고 bool 값을 value로 넣어서  
bool이 true라면 값이 있었다는 뜻이므로 cnt를 해줬다.

 

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

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

	int N, M;
	string str, res;
	map <string, bool> m;

	cin >> N >> M;
	for (int i = 0; i < N; i++) {
		cin >> str;
		m[str] = true;
	}
	int cnt = 0;
	while (M--) {
		cin >> res;
		if (m[res]) cnt++;
	}
	cout << cnt;
}

 

시간초과 나는 코드

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

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

	int N, M;
	string str[10001], res;

	cin >> N >> M;
	for (int i = 0; i < N; i++) {
		cin >> str[i];
	}

	int cnt = 0;
	while (M--) {
		cin >> res;
		for (int i = 0; i < N;i++) {
			if (res == str[i]) cnt++;
		}
	}
	cout << cnt;
}