Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Union-Find Basics

Union-Find Basics

I. Concept and Introduction

Union-Find is a tree-like data structure used to handle the merging and querying of disjoint sets.

The idea of Union-Find is to use an array to represent the whole forest (parent); the root of a tree uniquely identifies a set. As long as we find the tree root of an element, we can determine which set it belongs to.

II. Applicability Notes

Union-Find is used in some set application problems with N elements. We usually start by letting each element form a single-element set, then merge the sets containing elements belonging to the same group in a certain order, repeatedly finding which set an element is in along the way. This process may not seem complicated, but when the amount of data is huge, describing it with other data structures often requires too much space for a computer to bear, and cannot produce results in a short time, so Union-Find must be used.

III. Basic data representation of Union-Find

As shown in the figure above

0-4

The following are all

0

,

5-9

The following are all

1

, meaning

0、1、2、3、4

these five elements are connected,

5、6、7、8、9

these five elements are connected.

As in the figure above again 0、2、4、6、8 The following are all 0 this set, indicating 0、2、4、6、8 these five elements are connected,1、3、5、7、9 The following are all 1 this set, indicating 0,1、3、5、7、9 these five elements are connected.

Construct a class UnionFind; initialize it so that each id[i] points to itself, with no elements merged:

...

public

UnionFind1

(

int

n

)

{

        count

=

n

;

        id

=

new

int

[

n

]

;

       

// initialize; each id[i] points to itself, with no elements merged

       

for

(

int

i

=

0

;

i

<

n

;

i

++

)

            id

[

i

]

=

i

;

   

}

...

Java Example Code

Source code package download:Download

UnionFind.java file code:

package

runoob.union

;

public

class

UnionFind

{

   

private

int

[

]

id

;

   

// number of data items

   

private

int

count

;

   

public

UnionFind1

(

int

n

)

{

        count

=

n

;

        id

=

new

int

[

n

]

;

       

for

(

int

i

=

0

;

i

<

n

;

i

++

)

            id

[

i

]

=

i

;

   

}

}