public class QuickFindUF extends java.lang.Object
This implementation uses quick find. Initializing a data structure with N objects takes linear time. Afterwards, find, connected, and count takes constant time but union takes linear time.
For additional documentation, see Section 1.5 of Algorithms, 4th Edition, by Robert Sedgewick and Kevin Wayne.
Constructor and Description |
---|
QuickFindUF(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 objects 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 object p.
|
static void |
main(java.lang.String[] args)
Reads in a sequence of pairs of integers (between 0 and N-1) from standard input,
where each integer represents some object;
if the objects are in different components, merge the two components
and print the pair to standard output.
|
void |
union(int p,
int q)
Merge components containing p and q.
|
public QuickFindUF(int N)
N
- the number of objectsjava.lang.IllegalArgumentException
- if N < 0public int count()
public int find(int p)
p
- the integer representing one objectjava.lang.IndexOutOfBoundsException
- unless 0 <= p < Npublic boolean connected(int p, int q)
p
- the integer representing one objectq
- the integer representing the other objectjava.lang.IndexOutOfBoundsException
- unless both 0 <= p < N and 0 <= q < Npublic void union(int p, int q)
p
- the integer representing one objectq
- the integer representing the other objectjava.lang.IndexOutOfBoundsException
- unless both 0 <= p < N and 0 <= q < Npublic static void main(java.lang.String[] args)