문제

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

접근방법

Disjoint-set (Union-Find)

풀이코드

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

public class Main {
	
	static int N, M;
	static int[] parents;
	
	public static void main(String[] args) throws NumberFormatException, IOException {
		// 1. 입력 및 초기화
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(in.readLine(), " ");
		N = Integer.parseInt(st.nextToken());
		M = Integer.parseInt(st.nextToken());
		
		parents = new int[N+1];
		Arrays.fill(parents, -1);
		
		// 2. UNION-FIND
		StringBuilder sb = new StringBuilder();
		for(int i=0; i<M; i++) {
			st = new StringTokenizer(in.readLine(), " ");
			int check = Integer.parseInt(st.nextToken());
			int a  = Integer.parseInt(st.nextToken());
			int b  = Integer.parseInt(st.nextToken());
			
			if(check == 0) {
				union(a, b);
			} else {
				boolean ans = checking(a, b);
				sb.append(ans == true ? "YES" : "NO").append("\n");
			}
			
		}
		// 3. Answer
		System.out.println(sb.toString().trim());
	}
	
	public static int find(int a) {
		if(parents[a] < 0) return a;
		return parents[a] = find(parents[a]);
	}
	
	public static boolean checking(int a, int b) {
		int n1 = find(a);
		int n2 = find(b);
		
		if(n1 == n2) return true;
		else return false;
	}
	
	public static void union(int a, int b) {
		int n1 = find(a);
		int n2 = find(b);
		
		if(n1 != n2) {
			parents[n2] = n1;
		}
	}
	
}