백준 1764 듣보잡 C++

2022. 5. 19. 12:12알고리즘

728x90

N과 M 이 주어지는데 이때,  N + M만큼 받을 때 한 배열에 동시에 다 넣고 그 배열을 n+m-1만큼 돌면서 앞의 값이랑 뒤의 값이 같으면 다른 배열에 넣고 따로 나중에 출력해주면 쉽게 풀 수 있다. 

map 알고리즘으로도 푸는 방법이 있는데 나중에 풀면 따로 올리겠습니다.

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int n, m;
	cin >> n >> m;
	vector <string> str;

	for (int i = 0; i < n + m; i++) {
		string st;
		cin >> st;
		str.push_back(st);
	}

	sort(str.begin(), str.end());

	vector <string> s;
	for (int i = 0; i < n + m - 1; i++) {
		if (str[i] == str[i + 1]) {
			s.push_back(str[i]);
		}
	}
	cout << s.size() << '\n';
	for (int i = 0; i < s.size(); i++) {
		cout << s[i] << '\n';
	}

	return 0;
}
728x90