🔒 문제
1822번: 차집합
첫째 줄에는 집합 A의 원소의 개수 n(A)와 집합 B의 원소의 개수 n(B)가 빈 칸을 사이에 두고 주어진다. (1 ≤ n(A), n(B) ≤ 500,000)이 주어진다. 둘째 줄에는 집합 A의 원소가, 셋째 줄에는 집합 B의 원소
www.acmicpc.net
🔑 알고리즘
트리셋(TreeSet)
💡 풀이
차집합을 구현하는 문제로
말 그대로 두 개의 집합 Set을 두고,
A 집합에서 B 집합의 원소를 제거하고 출력하면 된다.
출력 조건이 오름차순 정렬이므로 TreeSet을 이용하면 편하다.
✏️ 코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
TreeSet<Integer> A = new TreeSet<>();
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
int nA = Integer.parseInt(st.nextToken());
int nB = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine(), " ");
for (int i = 0; i < nA; i++)
A.add(Integer.parseInt(st.nextToken()));
st = new StringTokenizer(br.readLine(), " ");
for (int i = 0; i < nB; i++)
A.remove(Integer.parseInt(st.nextToken()));
sb.append(A.size()).append("\n");
for(int a : A)
sb.append(a).append(" ");
System.out.println(sb);
}
}
'Algorithm > 백준(BOJ)' 카테고리의 다른 글
[백준] 2637. 장난감 조립 (Java) (1) | 2022.09.16 |
---|---|
[백준] 2003. 수들의 합2 (Java) (0) | 2022.09.15 |
[백준] 2252. 줄 세우기 (Java) (0) | 2022.09.13 |
[백준] 14267. 회사 문화 1 (Java) (0) | 2022.09.13 |
[백준] 1715. 카드 정렬하기 (Java) (0) | 2022.09.13 |