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

📔문제

자연수를 원소로 갖는 공집합이 아닌 두 집합 AB가 있다. 이때, 두 집합의 대칭 차집합의 원소의 개수를 출력하는 프로그램을 작성하시오.

두 집합 AB가 있을 때, (A-B)(B-A)의 합집합을 AB의 대칭 차집합이라고 한다.

예를 들어, A = { 1, 2, 4 } 이고, B = { 2, 3, 4, 5, 6 } 라고 할 때, A-B = { 1 } 이고, B-A = { 3, 5, 6 } 이므로, 대칭 차집합의 원소의 개수는 1 + 3 = 4개이다.


📝입력

첫째 줄에 집합 A의 원소의 개수와 집합 B의 원소의 개수가 빈 칸을 사이에 두고 주어진다.
둘째 줄에는 집합 A의 모든 원소가, 셋째 줄에는 집합 B의 모든 원소가 빈 칸을 사이에 두고 각각 주어진다. 각 집합의 원소의 개수는 200,000을 넘지 않으며, 모든 원소의 값은 100,000,000을 넘지 않는다.


📺출력

첫째 줄에 대칭 차집합의 원소의 개수를 출력한다.


📝예제 입력 1

3 5
1 2 4
2 3 4 5 6

📺예제 출력 1

4

🔍출처

-문제를 만든 사람: author5


🧮알고리즘 분류

  • 자료 구조
  • 해시를 사용한 집합과 맵
  • 트리를 사용한 집합과 맵

📃소스 코드

import java.io.*;
import java.util.HashMap;
import java.util.HashSet;

public class Code1269 {
    public static void main(String[] args) throws IOException {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        String[]counts=br.readLine().split(" ");

        int Acount=Integer.valueOf(counts[0]); //A집합 수
        int Bcount=Integer.valueOf(counts[1]); //B집합 수

        String[]As=br.readLine().split(" ");
        String[]Bs=br.readLine().split(" ");

        br.close();

        HashSet<Integer> answer=new HashSet<>();
        for(int i=0;i<Acount;i++){
            answer.add(Integer.valueOf(As[i]));
        }
        for(int i=0;i<Bcount;i++){
            if(answer.contains(Integer.valueOf(Bs[i]))){
                answer.remove(Integer.valueOf(Bs[i]));
            }
            else{
                answer.add(Integer.valueOf(Bs[i]));
            }

        }

        BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));
        bw.write(String.valueOf(answer.size()));

        bw.flush();
        bw.close();
    }
}

📰출력 결과


📂고찰

HashSet<>을 사용해서, 만약 Bs[i]의 값이 이미 저장되어있으면, 그 값을 없애버리는 식으로 바꿨더니 시간초과도 안뜨고 잘 통과했다.

profile
MySQL DBA 신입 지원

0개의 댓글