알고리즘 문제/BOJ
1764번 듣보잡
parkit
2019. 1. 2. 20:04
728x90
반응형
https://www.acmicpc.net/problem/1764
2가지 해결 방법이 있다.
1. C++ STL map 이용(map은 자동 사전순 정렬, 완전 이진 트리 구조)
2. 이분탐색 이용
1. C++ STL map 이용
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | #include <iostream> #include <queue> #include <stack> #include <cstdio> #include <vector> #include <cstring> #include <string> #include <math.h> #include <algorithm> #include <map> using namespace std; int N = 0, M = 0; int main(void) { int cnt = 0; string s; scanf("%d %d", &N, &M); map<string, int> m; for (int i = 0; i < N; i++) { cin >> s; m[s] = 1; } for (int i = 0; i < M; i++) { cin >> s; if (m.count(s) == 0) { m[s] = 1; } else { ++cnt; ++m[s]; } } printf("%d\n", cnt); auto itr = m.begin(); while (itr != m.end()) { if (itr->second == 2) { cout << itr->first << '\n'; } ++itr; } return 0; } | cs |
2. 이분탐색 이용
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | #include <iostream> #include <queue> #include <stack> #include <cstdio> #include <vector> #include <cstring> #include <string> #include <math.h> #include <algorithm> #include <map> using namespace std; int N = 0, M = 0; vector<string> v, ans; bool bs(int left, int right, string s) { while (left <= right) { int middle = (left + right) / 2; if (v.at(middle) == s) return true; else if (v.at(middle) < s) left = middle + 1; else if (v.at(middle) > s) right = middle - 1; } return false; } int main(void) { int cnt = 0; string s; scanf("%d %d", &N, &M); for (int i = 0; i < N; i++) { cin >> s; v.push_back(s); } sort(v.begin(), v.end()); for (int i = 0; i < M; i++) { cin >> s; if (bs(0, v.size() - 1, s)) { ans.push_back(s); } } sort(ans.begin(), ans.end()); printf("%d\n", ans.size()); for (auto i : ans) cout << i << '\n'; return 0; } | cs |
728x90
반응형