티스토리 뷰
요약
- 맵을 통한 중복값 처리
풀이과정
1. 데이터 처리
시간초과가 나지 않고 중복값을 처리하기 위해 맵 구조를 사용한다.
정렬될 필요가 있고, 사전순 정렬이기 때문에 map을 그대로 쓴다.
(혹은 unordred_map을 사용하고 추후에 sort해주는 방법도 있다.)
int n, m;
cin >> n >> m;
cin.ignore();
map<string,int> map;
vector<string> both_str;
for(int i = 0 ; i < n+m; i++) {
string str;
getline(cin,str);
map[str]++;
}
cin.ignore() 해주지 않으면 공백값이 처음으로 들어가서 그걸 무시하기 위해 넣었다.
이렇게 map에 예쁘게 저장되고, 중복된 값은 value가 2이다.
2. vector에 재처리 및 출력
문제 조건에서 두 집합 내에서 중복값은 발생하지 않는다 명시했으므로 2이면 vector에 집어넣는다.
개수를 맨 처음에 출력해야 하므로 그냥 vector에 넣어줬다.
for(auto item : map) {
if(item.second == 2) {
both_str.push_back(item.first);
}
}
cout << both_str.size() << '\n';
for(auto str : both_str) {
cout << str << '\n';
}
코드
#define LOCAL
#include <bits/stdc++.h>
using namespace std;
int main() {
#ifdef LOCAL
freopen("input.txt","r",stdin);
#endif
cin.tie(0) -> sync_with_stdio(0);
int n, m;
cin >> n >> m;
cin.ignore();
map<string,int> map;
vector<string> both_str;
for(int i = 0 ; i < n+m; i++) {
string str;
getline(cin,str);
map[str]++;
}
for(auto item : map) {
if(item.second == 2) {
both_str.push_back(item.first);
}
}
cout << both_str.size() << '\n';
for(auto str : both_str) {
cout << str << '\n';
}
}
다른 사람의 풀이
비슷했다.
'■ 알고리즘 > ◻ 백준' 카테고리의 다른 글
[C++]3111번: 검열 (0) | 2024.05.05 |
---|---|
[C++]4949번: 균형잡힌 세상 (0) | 2023.03.05 |
[C++]1541번: 잃어버린 괄호 (0) | 2023.02.26 |
[C++]1427번: 소트인사이드 (0) | 2023.02.26 |
[C++] 1181번: 단어 정렬 (0) | 2023.02.26 |