본문 바로가기
알고리즘/백준

[JAVA]백준_1717_집합의표현

by 박 현 황 2021. 3. 19.

문제링크

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

 

1717번: 집합의 표현

첫째 줄에 n(1 ≤ n ≤ 1,000,000), m(1 ≤ m ≤ 100,000)이 주어진다. m은 입력으로 주어지는 연산의 개수이다. 다음 m개의 줄에는 각각의 연산이 주어진다. 합집합은 0 a b의 형태로 입력이 주어진다. 이는

www.acmicpc.net

 

 

 

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

public class Main {

	static int N,M;
	static int parents[];
	
	static void make() {
		for(int i=0;i<=N;i++) parents[i] = i;
	}
	
	static int findSet(int a) {
		
		if(parents[a] == a) return a;
		
		return parents[a] = findSet(parents[a]);
	}
	static boolean union(int a,int b) {
		int aRoot = findSet(a);
		int bRoot = findSet(b);
		
		if(aRoot == bRoot) return false;
		
		parents[bRoot] = aRoot;
		return true;
	}
	
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		
		N = Integer.parseInt(st.nextToken());
		M = Integer.parseInt(st.nextToken());
		
		parents = new int[N+1];
		make();
		
		for(int i=0;i<M;i++) {
			st = new StringTokenizer(br.readLine());
			//합집합은 9
			//두 원소가 같은 집합에 포합되어 있는지는 1
			
			int n = Integer.parseInt(st.nextToken());
			int a = Integer.parseInt(st.nextToken());
			int b = Integer.parseInt(st.nextToken());
			
			if(n == 0) union(a, b);
			else {
				if(findSet(a) == findSet(b)) System.out.println("YES");
				else System.out.println("NO");
			}
		}
	}
}

 

make함수 -> 0부터 N까지 배열에 넣어준다

findSet함수 -> 나의 부모 찾아주는 함수

union 함수 ->합집합해주는 함수
     부모를 바꿔줌으로써 union 수행

'알고리즘 > 백준' 카테고리의 다른 글

[JAVA]백준_2573_빙산  (0) 2021.03.19
[JAVA]백준_16562_친구비  (0) 2021.03.19
[JAVA]백준_14889_스타트와 링크  (0) 2021.03.17
[JAVA]3709_레이저빔은 어디로  (0) 2021.03.17
[JAVA]백준_1260_DFS와 BFS  (0) 2021.03.16