PS/Algorithms

[Java] Union find - 같은 집합에 속하는지 검사

CalicoCat22 2022. 2. 9. 22:29

https://dolphins-it.tistory.com/223

 

유니온 파인드(with 백준1717)

유니온파인드란? 유니온 파인드는 상호 배타적 집합이라고도 하며 누군가 어떤 집합에 속해있는지 알아내기위해, 또는 집합끼리 합치기 위해 사용하는 자료구조이다. 구현 트리를 통해서 이 자

dolphins-it.tistory.com

1) union(int a, int b)

a, b의 각 루트를 찾아낸 후

루트를 연결해준다.

 

2) find(int x)

x의 루트 위치를 찾는다.

이 과정에서 최악의 케이스를 줄여주기 위해

찾아낸 루트에 모든 자식들을 직접 연결한다.

import java.util.*;
import java.io.*;

public class union_find {
    static FastScanner fs = new FastScanner();
    static PrintWriter pw = new PrintWriter(System.out);
    static int n, m;
    static int[] pp;

    public static void main(String[] args) {
        n = fs.nextInt();
        m = fs.nextInt();

        pp = new int[n + 1];
        for (int i=1;i<=n;i++) pp[i] = i;
        
        for (int i=0;i<m;i++){
            // int a = fs.nextInt(), b = fs.nextInt();
            
            // union(a, b);

            // int x = find(a);
            // int y = find(b);
        }
        pw.close();
    }

    static void union(int a, int b){
        int x = find(a);
        int y = find(b);
        pp[x] = y;
    }

    static int find(int x){
        if (x == pp[x]) return x;
        else{
            int y = find(pp[x]);
            pp[x] = y;
            return y;
        }
    }

    // ----------input function----------

    static void sort(int[] a) {
        ArrayList<Integer> L = new ArrayList<>();
        for (int i : a)
            L.add(i);
        Collections.sort(L);
        for (int i = 0; i < a.length; i++)
            a[i] = L.get(i);
    }

    static class FastScanner {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer("");

        String next() {
            while (!st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        int[] readArray(int n) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++)
                a[i] = nextInt();
            return a;
        }

        long nextLong() {
            return Long.parseLong(next());
        }
    }
}