본문 바로가기

백준

1269번: 대칭 차집합(Java)

 

 

 집합의 원소는 중복되지 않는다. 따라서 HastSet을 사용했다.

 

 

 

 

 

 

우선 집합 A와 B를 HashSet으로 선언한 후, 입력을 받는다

Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();//A 집합의 원소 수
int m = scanner.nextInt();//B 집합의 원소 수
HashSet<Integer> A = new HashSet<>();//A집합
HashSet<Integer> B = new HashSet<>();//B집합
int result = 0;//결과


//입력받는다
for(int i = 0; i<n; i++)
{
    A.add(scanner.nextInt());
}
for(int i = 0; i<m; i++)
{
    B.add(scanner.nextInt());
}

 

 

 

 

 

 

이제 대칭 차집합을 셀 차례이다.

A 집합의 모든 원소를 돌면서 B 집합에 존재하지 않는 원소가 A 집합에 있으면 result++ 을 해 준다.

마찬가지로 B 집합의 모든 원소를 돌면서 A 집합에 존재하지 않는 원소가 B 집합에 있으면 result++을 해 준다.

//A집합의 원소를 돌면서 B집합에 없을 경우 result++
for(Object i : A.toArray())
{
    if(!B.contains(i))
    {
        result++;
    }
}

//B집합의 원소를 돌면서 A집합에 없을 경우 result++
for(Object i : B.toArray())
{
    if(!A.contains(i))
    {
        result++;
    }
}


System.out.println(result);

 

 

 

 

 

 

 

<전체 코드>

import java.util.*;

public class Main
{
    public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();//A 집합의 원소 수
        int m = scanner.nextInt();//B 집합의 원소 수
        HashSet<Integer> A = new HashSet<>();//A집합
        HashSet<Integer> B = new HashSet<>();//B집합
        int result = 0;//결과


        //입력받는다
        for(int i = 0; i<n; i++)
        {
            A.add(scanner.nextInt());
        }
        for(int i = 0; i<m; i++)
        {
            B.add(scanner.nextInt());
        }

        //A집합의 원소를 돌면서 B집합에 없을 경우 result++
        for(Object i : A.toArray())
        {
            if(!B.contains(i))
            {
                result++;
            }
        }

        //B집합의 원소를 돌면서 A집합에 없을 경우 result++
        for(Object i : B.toArray())
        {
            if(!A.contains(i))
            {
                result++;
            }
        }


        System.out.println(result);
    }
}

'백준' 카테고리의 다른 글

11399번: ATM(Java)  (0) 2023.02.12
1406번: 에디터(Java)  (0) 2023.02.07
1620번: 나는야 포켓몬 마스터 이다솜(Java)  (0) 2023.01.31
10815번: 숫자 카드(Java)  (1) 2023.01.30
2477번: 참외밭(Java)  (1) 2023.01.30