public class UF extends java.lang.Object
The union-find data type models connectivity among a set of N sites, named 0 through N – 1. The is-connected-to relation must be an equivalence relation:
This implementation uses weighted quick union by rank with path compression
by halving.
Initializing a data structure with N sites takes linear time.
Afterwards, the union, find, and connected
operations take logarithmic time (in the worst case) and the
count operation takes constant time.
Moreover, the amortized time per union, find,
and connected operation has inverse Ackermann complexity.
For alternate implementations of the same API, see
QuickUnionUF
, QuickFindUF
, and WeightedQuickUnionUF
.
For additional documentation, see Section 1.5 of Algorithms, 4th Edition, by Robert Sedgewick and Kevin Wayne.
Constructor and Description |
---|
UF(int N)
Initializes an empty union-find data structure with N
isolated components 0 through N-1
|
Modifier and Type | Method and Description |
---|---|
boolean |
connected(int p,
int q)
Are the two sites p and q in the same component?
|
int |
count()
Return the number of components.
|
int |
find(int p)
Return the component identifier for the component containing site p.
|
static void |
main(java.lang.String[] args)
Reads in a an integer N and a sequence of pairs of integers
(between 0 and N-1) from standard input, where each integer
in the pair represents some site;
if the sites are in different components, merge the two components
and print the pair to standard output.
|
void |
union(int p,
int q)
Merge the component containing site p with the
the component containing site q.
|
public UF(int N)
N
- the number of sitesjava.lang.IllegalArgumentException
- if N < 0public int find(int p)
p
- the integer representing one objectjava.lang.IndexOutOfBoundsException
- unless 0 ≤ p < Npublic int count()
public boolean connected(int p, int q)
p
- the integer representing one siteq
- the integer representing the other sitejava.lang.IndexOutOfBoundsException
- unless
both 0 ≤ p < N and 0 ≤ q < Npublic void union(int p, int q)
p
- the integer representing one siteq
- the integer representing the other sitejava.lang.IndexOutOfBoundsException
- unless
both 0 ≤ p < N and 0 ≤ q < Npublic static void main(java.lang.String[] args)