-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickUnionUF.cpp
More file actions
78 lines (63 loc) · 1.22 KB
/
QuickUnionUF.cpp
File metadata and controls
78 lines (63 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
using namespace std;
class QuickUnionUF
{
private:
int *id;
int num;
public:
QuickUnionUF(int n)
{
id = new int[n];
for(int i=0;i<n;i++)
id[i] = i;
num = n;
cout << "New UF obj with elements " << num << endl;
}
~QuickUnionUF()
{
delete id;
num = 0;
}
int root(int p)
{
while(id[p] != p)
p = id[p];
return p;
}
bool Connected(int p, int q)
{
if(root(p) == root(q))
{
cout << p << " and " << q << " are connected !" << endl;
return 1;
}
else
{
cout << p << " and " << q << " are NOT connected !" << endl;
return 0;
}
}
void Union(int p, int q)
{
int proot = root(p);
int qroot = root(q);
id[proot] = qroot;
cout << p << " and " << q << " union !" << endl;
return ;
}
};
int main()
{
QuickUnionUF oQuickUnionUF(10);
oQuickUnionUF.Union(0,5);
oQuickUnionUF.Union(6,5);
oQuickUnionUF.Union(2,1);
oQuickUnionUF.Union(7,1);
oQuickUnionUF.Union(3,4);
oQuickUnionUF.Union(9,4);
oQuickUnionUF.Union(8,3);
oQuickUnionUF.Connected(0,6);
oQuickUnionUF.Connected(7,6);
return 0;
}