티스토리 뷰


[백준 1717번] 집합의 표현 URL



기본적인 Union-Find 문제이므로 이전 포스팅 글을 참고하시기 바랍니다.

2019/03/25 - [알고리즘 이론] - [알고리즘] 유니온 파인드 (Union-Find) :: 늦깎이 IT



[소스 코드]


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.StringTokenizer;
 
public class Main {
 
    static int N, M;
 
    static int[] dirX = new int[] { 001-1 };
    static int[] dirY = new int[] { 1-100 };
 
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static StringTokenizer st;
 
    public static void main(String[] args) throws IOException {
 
        st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());
 
        int[] parent = new int[N + 1];
        for (int i = 0; i < N + 1; i++)
            parent[i] = i;
 
        for (int i = 0; i < M; i++) {
            st = new StringTokenizer(br.readLine());
            int command = Integer.parseInt(st.nextToken());
            int a = Integer.parseInt(st.nextToken());
            int b = Integer.parseInt(st.nextToken());
            if (command == 0)
                union(parent, a, b);
            else {
                if (find(parent, a, b))
                    System.out.println("YES");
                else
                    System.out.println("NO");
            }
        }
    }
 
    public static int getParent(int[] parent, int node) {
 
        if (parent[node] == node)
            return node;
        else
            return parent[node] = getParent(parent, parent[node]);
    }
 
    public static boolean find(int[] parent, int a, int b) {
 
        int parent1 = getParent(parent, a);
        int parent2 = getParent(parent, b);
 
        if (parent1 == parent2)
            return true;
        else
            return false;
    }
 
    public static void union(int[] parent, int a, int b) {
 
        int parent1 = getParent(parent, a);
        int parent2 = getParent(parent, b);
 
        if (parent1 <= parent2)
            parent[parent2] = parent1;
        else
            parent[parent1] = parent2;
        
    }
 
}
 
cs


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함