문제 링크 https://www.acmicpc.net/problem/14425

문제

총 N개의 문자열로 이루어진 집합 S가 주어진다.

입력으로 주어지는 M개의 문자열 중에서 집합 S에 포함되어 있는 것이 총 몇 개인지 구하는 프로그램을 작성하시오.

입력

첫째 줄에 문자열의 개수 N과 M (1 ≤ N ≤ 10,000, 1 ≤ M ≤ 10,000)이 주어진다.

다음 N개의 줄에는 집합 S에 포함되어 있는 문자열들이 주어진다.

다음 M개의 줄에는 검사해야 하는 문자열들이 주어진다.

입력으로 주어지는 문자열은 알파벳 소문자로만 이루어져 있으며, 길이는 500을 넘지 않는다. 집합 S에 같은 문자열이 여러 번 주어지는 경우는 없다.

출력

첫째 줄에 M개의 문자열 중에 총 몇 개가 집합 S에 포함되어 있는지 출력한다.

풀이 과정

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

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

#include <vector>
#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 <vector>
#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;
}

댓글남기기