Skip to content

Commit b122bbb

Browse files
committed
Add Quick-Find.
1 parent 7a6e5b4 commit b122bbb

File tree

5 files changed

+49
-0
lines changed

5 files changed

+49
-0
lines changed

Disjoint-Sets/_quickFind.hpp

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Quick-Find: O(1) for Find and O(n) for Union.
2+
3+
class DisjointSet {
4+
public:
5+
int *_set, n;
6+
7+
DisjointSet(int n) {
8+
_set = new int[n];
9+
this->n = n;
10+
}
11+
12+
void makeSet(int m) {
13+
_set[m] = m;
14+
return;
15+
}
16+
17+
int find(int m) {
18+
return _set[m];
19+
}
20+
21+
void Union(int a, int b) {
22+
int in = _set[a];
23+
int IN = _set[b];
24+
25+
for (int t=0;t<this->n;++t) {
26+
if (this->_set[t] == in)
27+
this->_set[t] = IN;
28+
}
29+
return;
30+
}
31+
};
32+

Disjoint-Sets/a.out

-62.8 KB
Binary file not shown.

Disjoint-Sets/quickFind.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
#include <iostream>
2+
using namespace std;
3+
#include "_quickFind.hpp"
4+
5+
int main() {
6+
unique_ptr<DisjointSet> ds = make_unique<DisjointSet>(6);
7+
8+
ds->makeSet(1);
9+
ds->makeSet(2);
10+
ds->makeSet(3);
11+
ds->makeSet(4);
12+
13+
cout << ds->find(3) << " ";
14+
ds->Union(3, 4);
15+
ds->Union(3, 1);
16+
cout << ds->find(4) << " ";
17+
}

0 commit comments

Comments
 (0)