A union-find data structure, also known as a disjoint-set data structure, is a data structure that keeps track of a set of elements partitioned into a number of disjoint (non-overlapping) subsets. It supports two main operations:
find
: determine which subset a particular element is in.union
: join two subsets into a single subset.To create a union-find data structure in Java, you can define a class that implements the UnionFind
interface, which defines the find
and union
operations.
Here is an example of how you can create a union-find data structure in Java:
refer to:lautturi.comimport java.util.Arrays; public class UnionFind { private int[] parents; // Parent of each element private int[] ranks; // Rank of each element // Initialize the union-find data structure with n elements public UnionFind(int n) { parents = new int[n]; ranks = new int[n]; for (int i = 0; i < n; i++) { parents[i] = i; // Set the parent of each element to itself ranks[i] = 0; // Set the rank of each element to 0 } } // Find the parent of element x public int find(int x) { if (parents[x] != x) { // Set the parent of x to the parent of its parent parents[x] = find(parents[x]); } return parents[x]; } // Join the sets containing element x and element y public void union(int x, int y) { int xParent = find(x); int yParent = find(y); if (xParent == yParent) { // x and y are already in the same set return; } // Set the parent of y to x if x has a higher rank // Otherwise, set the parent of x to y if (ranks[xParent] < ranks[yParent]) { parents[xParent] = yParent; } else if (ranks[xParent] > ranks[yParent]) { parents[yParent] = xParent; } else { // x and y have the same rank, so set the parent of y to x // and increment the rank of x parents[yParent] = xParent; ranks[xParent]++; } } // Check if element x is in the same set as element y public boolean isConnected(int x, int y) { return find(x) == find(y); } @Override public String toString() { return Arrays.toString(parents); } }
This class defines a union-find data structure with n
elements, where n
is the number of elements passed to the constructor. It stores the parent of each element in an array called parents
, and the rank of each element in an array called ranks
. The find
method returns the parent of an element by recursively calling itself on the parent until it reaches the root element, which is an element whose parent is itself.