-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnionFind.cpp
More file actions
81 lines (73 loc) · 1.51 KB
/
UnionFind.cpp
File metadata and controls
81 lines (73 loc) · 1.51 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
79
80
81
#include <iostream>
#include <cassert>
using namespace std;
class UnionFind{
private:
int* parent;
// int* size;
int* rank;
int count;
public:
UnionFind(int count)
{
parent = new int[count];
rank = new int[count];
this->count = count;
for(int i=0; i<count; i++)
{
parent[i]=i;
rank[i]=1;
}
}
~UnionFind()
{
delete[] parent;
delete[] rank;
}
int find(int p)
{
assert(p>=0&&p<count);
// while(p!=parent[p])
// {
// parent[p] = parent[parent[p]];//路径压缩
// p = parent[p];
// }
if(p!=parent[p])
{
parent[p] = find(parent[p]);//可预测,可不递归
}
return parent[p];
}
bool isConnected(int p, int q)
{
return find(p) == find(q);
}
void unionElements(int p, int q)
{
int pRoot = find(p);
int qRoot = find(q);
if(qRoot==pRoot)
return;
if(rank[pRoot]<rank[qRoot])
{
parent[pRoot] = qRoot;
}
else if(rank[pRoot]>rank[qRoot])
{
parent[qRoot] = pRoot;
}
else{
parent[pRoot] = qRoot;
rank[qRoot]++;
}
}
};
int main()
{
UnionFind* uf = new UnionFind(100);
uf->unionElements(1,9);
cout << uf->find(1) << endl;
cout << uf->find(9) << endl;
cout << uf->isConnected(1,9) << endl;
return 0;
}