풀이)
예시를 봤을 때
0, 1, 2... 7의 집합을 생성하고, 8번 연산을 한다는 뜻.
0 1 3 이란 1과 3을 합친다는 것이고
1 1 7 이란 1과 7의 대표값이 같은지 확인한다는 것이다
즉 union find 연산으로 계산할 수 있다.
내 코드)
// 백준 온라인 저지 1717번
import java.io.*;
import java.util.*;
public class Main{
static int Arr[];
static void union(int a, int b) {
a = find(a);
b = find(b);
if(a != b) {
Arr[b] = a;
}
}
static int find(int a) {
if(Arr[a] == a) {
return a;
}
return Arr[a] = find(Arr[a]);
}
public static void main(String[]args) throws IOException{
// 입력.
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(bf.readLine());
int n = Integer.parseInt(st.nextToken()); //집합 개수
int m = Integer.parseInt(st.nextToken()); //연산 횟수
// 유니온 파인드를 위해 배열 생성
Arr = new int[n+1];
for(int i=0;i<=n;i++) {
Arr[i] = i;
}
for(int i=0;i<m;i++) {
st = new StringTokenizer(bf.readLine());
int cal = Integer.parseInt(st.nextToken());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
if(cal==0) {
union(a, b);
}else {
int a_rep = find(a);
int b_rep = find(b);
if(a_rep == b_rep) System.out.println("YES");
if(a_rep != b_rep) System.out.println("NO");
}
}
}
}
개발자로서 배울 점이 많은 글이었습니다. 감사합니다.