Shiny Sky Blue Star

백준 문제 풀이/백준 (JAVA)

JAVA 백준 1269 대칭 차집합 (해시, 맵)

gamja00 2025. 4. 22. 18:59

 

https://www.acmicpc.net/problem/1269

 


문제

  1. 첫째 줄에 A (1 <= A <= 200000), B (1 <= B <= 200000) 주어진다.
  2. 둘째 줄에 집합 A의 원소가 공백으로 구분되어 A개가 입력된다.
  3. 셋째 줄에 집합 B의 원소가 공백으로 구분되어 B개가 입력된다.
  4. 두 집합의 대칭 차집합((A - B)와 (B - A)의 합집합)의 원소 개수를 출력하라.

 

hashSet과 배열 리스트를 이용하여 각 hashSet에 배열에 있는 원소가 들어있는지 체크하여 갯수를 모두 더해 출력하면 된다.

 

 

최종 코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
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 A = Integer.parseInt(st.nextToken());
        int B = Integer.parseInt(st.nextToken());

        int[] AList = new int[A];
        int[] BList = new int[B];

        HashSet<Integer> AMap = new HashSet<>();
        HashSet<Integer> BMap = new HashSet<>();

        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < A; i++) {
            int num = Integer.parseInt(st.nextToken());
            AMap.add(num);
            AList[i] = num;
        }
        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < B; i++) {
            int num = Integer.parseInt(st.nextToken());
            BMap.add(num);
            BList[i] = num;
        }

        int ACount = 0;
        int BCount = 0;

        for (int i = 0; i < A; i++) {
            if (!BMap.contains(AList[i])) {
                ACount++;
            }
        }
        for (int i = 0; i < B; i++) {
            if (!AMap.contains(BList[i])) {
                BCount++;
            }
        }

        System.out.println(ACount + BCount);
    }
}