public class QuickFindUF extends 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 sites p and q/tt> in the same component?
|
int |
count()
Returns the number of components.
|
int |
find(int p)
Returns the component identifier for the component containing site p.
|
static void |
main(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)
Merges the component containing sitep with the component
containing site q.
|
public QuickFindUF(int N)
N - the number of objectsIllegalArgumentException - if N < 0public int count()
public int find(int p)
p - the integer representing one siteIndexOutOfBoundsException - unless 0 <= p < Npublic boolean connected(int p,
int q)
p - the integer representing one siteq - the integer representing the other siteIndexOutOfBoundsException - 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 siteIndexOutOfBoundsException - unless both 0 <= p < N and 0 <= q < Npublic static void main(String[] args)
Copyright © 2014. All Rights Reserved.