새소식

Algorithm/BOJ

(JAVA) 백준 1269번 : 대칭 차집합

  • -
728x90

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

 

1269번: 대칭 차집합

첫째 줄에 집합 A의 원소의 개수와 집합 B의 원소의 개수가 빈 칸을 사이에 두고 주어진다. 둘째 줄에는 집합 A의 모든 원소가, 셋째 줄에는 집합 B의 모든 원소가 빈 칸을 사이에 두고 각각 주어

www.acmicpc.net

Counting 정렬로 풀이를 시도했으나 런타임 에러 (ArrayIndexOutOfBounds) 가 발생하여 추가적인 풀이를 고민했다.

근본적으로 문제를 생각했을 때 둘의 교집합을 구하고 [A집합 - 교집합] + [B집합 - 교집합] 을 구하면 된다는 결론이 나왔다.

즉, A집합 + B집합 - 교집합 X 2 를 해주면 된다.

교집합을 구하는 방식은 HashMapcontainsKey를 사용했고 풀이는 아래와 같다.

 

소스코드

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

import java.util.StringTokenizer;
import java.util.HashMap;



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(), " ");

		HashMap<Integer, Integer> map = new HashMap<>();

		int N = Integer.parseInt(st.nextToken());
		int M = Integer.parseInt(st.nextToken());

		int count = 0;
		int S = N+M;
		st = new StringTokenizer(br.readLine(), " ");

		while(N-- >0)
		{
			map.put(Integer.parseInt(st.nextToken()), 0);
		}

		st = new StringTokenizer(br.readLine(), " ");

		while(M-- >0)
		{
			if(map.containsKey(Integer.parseInt(st.nextToken()))) count++;
		}

		System.out.println(S-2*count);
	}
}
728x90
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.