[백준] 1269번 - 대칭 차집합 [Java][C++]
[백준] 1269번 - 대칭 차집합 [Java][C++]
1. 문제 풀이
두 집합 $A$, $B$ 에 대해 $A - B$ 와 $B - A$ 의 합집합인 대칭 차집합을 구하는 문제로 대칭 차집합의 크기는 두 집합의 크기에서 두 집합의 교집합의 크기의 두 배를 빼주면 된다.
2. 코드
1. 해시를 사용한 집합과 맵 [Java]
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
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
Set<Integer> A = new HashSet<>();
st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
A.add(Integer.parseInt(st.nextToken()));
}
Set<Integer> B = new HashSet<>();
st = new StringTokenizer(br.readLine());
for (int i = 0; i < M; i++) {
B.add(Integer.parseInt(st.nextToken()));
}
int cnt = 0;
for (int n : A) {
if (B.contains(n)) cnt++;
}
System.out.println(N + M - 2 * cnt);
}
}
2. 해시를 사용한 집합과 맵 [C++]
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
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
unordered_set<int> a;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
a.insert(x);
}
unordered_set<int> b;
for (int i = 0; i < m; i++) {
int x;
cin >> x;
b.insert(x);
}
int cnt = 0;
for (int x : a) {
if (b.count(x)) cnt++;
}
cout << n + m - 2 * cnt;
}
3. 풀이 정보
1. 해시를 사용한 집합과 맵 [Java]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| Java 11 | 632 ms | 81276 KB | 907 B |
2. 해시를 사용한 집합과 맵 [C++]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| C++ 17 | 120 ms | 20544 KB | 500 B |
This post is licensed under CC BY 4.0 by the author.