Question: 1 Instructions Implement two algorithms 1 . UNION - FIND: You must implement this data structure where UNION operation is done by rank 2 .

1 Instructions
Implement two algorithms
1. UNION-FIND: You must implement this data structure where
UNION operation is done by rank
2. UNION-FIND-WITH-PATH-COMPRESSION: You must implement this data structure where
UNION operation is done by rank and
FIND-SET is implemented with path compression
2.1 Test Cases
Each test case will be input in the form of a text file
Input format
First line - n (Number of elements)
Number of UNION Operations will be n 1
Second line - m (Number of FIND-SET Operations)
Next m +(n 1) lines will either be a
1. Union operation Uxy, where 1<= x, y <= n
2. Find operation Fx, where 1<= x <= n
Output format
m lines for each FIND-SET operation, where each line outputs the root/representative
of the set to which x belongs
Sample Input
4
6
F 2
U 12
F 2
U 23
F 3
F 2
F 4
U 14
F 4
Sample Output
2
1
1
1
4
1
Details
Uxy should merge the two sets containing x and y
Definition of Rank
For union by rank, a node stores its rank which is an upper bound for its height.
When a node is initialized, its rank is set to zero.
To merge trees with roots x and y, first compare their ranks.
If the ranks are different, then the larger rank tree becomes the parent, and the
ranks of x and y do not change.
Tie Break
Let x in T1, y in T2
If rank(T1)= rank(T2), root of T1 must be made the root of the resultant
merged tree
Fx should output the root of the tree to which x belongs in the output file
2.2 Test Case Execution
The input file name will be given as a command line argument with the option -i or
--input [See below for example]
Assume the file exists in the current directory where the program is located
Output file must be named output.txt [See below for example]
Output file must be created in the current directory where the program is located
See the following commands for python (but could be extrapolated for any other language)
$ python3 unionf i n d . py i t e s t 1. t x t
$ python3 unionf i n d . py i n p u t t e s t 1. t x t
In this case, the output file must be created in the current directory with the name
test 1 output.txt

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!