Published online by Cambridge University Press: 05 June 2012
This appendix describes a simple yet very efficient Perl solution to a problem known as the disjoint sets problem, the dynamic equivalence relation problem, or the unionfind problem. This problem appears in applications with the following scenario.
Each one of a finite set of keys is assigned to exactly one of a number of classes. These classes are the “disjoint sets” or the partitions of an equivalence relation. Often, the set of keys is known in advance, but this is not necessary to use our Perl package.
Initially, each key is in a class by itself.
As the application progresses, classes are joined together to form larger classes; classes are never divided into smaller classes. (The operation of joining classes together is called union or merge.)
At any moment, it must be possible to determine whether two keys are in the same class or in different classes.
To solve this problem, we create a package named UnionFind. Objects of type UnionFind represent an entire collection of keys and classes. The three methods of this package are:
$uf = UnionFind– > new(), which creates a new collection of disjoint sets, each of which has only one element;
$uf– > inSameSet($key1,$key2), which returns true if its two arguments are elements of the same disjoint set or false if not;
$uf– > union($key1,$key2), which combines the sets to which its two arguments belong into a single set.
To save this book to your Kindle, first ensure [email protected] is added to your Approved Personal Document E-mail List under your Personal Document Settings on the Manage Your Content and Devices page of your Amazon account. Then enter the ‘name’ part of your Kindle email address below. Find out more about saving to your Kindle.
Note you can select to save to either the @free.kindle.com or @kindle.com variations. ‘@free.kindle.com’ emails are free but can only be saved to your device when it is connected to wi-fi. ‘@kindle.com’ emails can be delivered even when you are not connected to wi-fi, but note that service fees apply.
Find out more about the Kindle Personal Document Service.
To save content items to your account, please confirm that you agree to abide by our usage policies. If this is the first time you use this feature, you will be asked to authorise Cambridge Core to connect with your account. Find out more about saving content to Dropbox.
To save content items to your account, please confirm that you agree to abide by our usage policies. If this is the first time you use this feature, you will be asked to authorise Cambridge Core to connect with your account. Find out more about saving content to Google Drive.