본문 바로가기
Programming Solve/BOJ

BOJ 1764 듣보잡 / C++

by msm1029 2021. 7. 16.
반응형

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

 

1764번: 듣보잡

첫째 줄에 듣도 못한 사람의 수 N, 보도 못한 사람의 수 M이 주어진다. 이어서 둘째 줄부터 N개의 줄에 걸쳐 듣도 못한 사람의 이름과, N+2째 줄부터 보도 못한 사람의 이름이 순서대로 주어진다.

www.acmicpc.net

 

풀이

n개의 문자열과 m개의 문자열을 입력받아 같은 문자열을 출력해주는 코드를 짜면 된다.

처음에는 2중 for문을 사용하는 풀이를 사용했지만 시간 초과가 나서 binary search를 이용하여 다시 풀었다.

참고로, binary search를 사용하기 위해선 정렬이 필요하다.

 

이중 for문 코드(시간 초과)

#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;

int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(nullptr); cout.tie(nullptr);

	int n, m, cnt = 0;
	cin >> n >> m;
	vector<string> names1;
	vector<string> names2;
	vector<string> ans;

	for (int i = 0; i < n; i++) {
		string tmp;
		cin >> tmp;
		names1.push_back(tmp);
	}

	for (int i = 0; i < m; i++) {
		string tmp;
		cin >> tmp;
		names2.push_back(tmp);
	}

	for (vector<string>::iterator it1 = names1.begin(); it1 != names1.end(); ++it1) {
		for (vector<string>::iterator it2 = names2.begin(); it2 != names2.end(); ++it2) {
			if (*it1 == *it2) {
				cnt++;
				ans.push_back(*it1);
			}
		}
	}

	sort(ans.begin(), ans.end());
	cout << cnt << '\n';
	for (int i = 0; i < ans.size(); i++) {
		cout << ans[i] << '\n';
	}
}

binary search 코드

#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;

int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(nullptr); cout.tie(nullptr);

	int n, m, cnt = 0;
	cin >> n >> m;
	vector<string> names;
	vector<string> ans;

	for (int i = 0; i < n; i++) {
		string tmp;
		cin >> tmp;
		names.push_back(tmp);
	}
	sort(names.begin(), names.end());

	for (int i = 0; i < m; i++) {
		string tmp;
		cin >> tmp;
		if (binary_search(names.begin(), names.end(), tmp)) {
			cnt++;
			ans.push_back(tmp);
		}
	}

	sort(ans.begin(), ans.end());
	cout << cnt << '\n';
	for (int i = 0; i < ans.size(); i++) {
		cout << ans[i] << '\n';
	}
}
반응형

'Programming Solve > BOJ' 카테고리의 다른 글

BOJ 10815 숫자 카드 / C++  (0) 2021.07.16
BOJ 1541 잃어버린 괄호 / C++  (0) 2021.07.16
BOJ 3046 / 10162 / 10930 / 16968 / Python  (0) 2021.03.20
BOJ 20953 / C++  (0) 2021.03.02
BOJ 11558 The game of death / C++  (0) 2021.02.12