Skip to content

Commit 93fd4e8

Browse files
committed
Union find template
1 parent 8078d83 commit 93fd4e8

File tree

5 files changed

+29
-38
lines changed

5 files changed

+29
-38
lines changed

.DS_Store

10 KB
Binary file not shown.

Segment_Tree/.DS_Store

8 KB
Binary file not shown.

Template/.DS_Store

8 KB
Binary file not shown.

Template/Graph/Uion_find.cpp

Lines changed: 0 additions & 38 deletions
This file was deleted.

Template/Graph/UnionFind.cpp

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class UnionFind {
2+
private:
3+
vector<int> parent, rank;
4+
int cnt;
5+
public:
6+
UnionFind(int cnt) : cnt(cnt) {
7+
parent = vector<int>(cnt);
8+
rank = vector<int>(cnt, 0);
9+
for (int i = 0; i < cnt; ++i) parent[i] = i;
10+
}
11+
int find(int p) {
12+
if (parent[p] == p) return p;
13+
return parent[p] = find(parent[p]);
14+
}
15+
bool connected(int p, int q) {
16+
return find(p) == find(q);
17+
}
18+
voparent connect(int p, int q) {
19+
int i = find(p), j = find(q);
20+
if (i == j) return;
21+
if (rank[i] < rank[j]) {
22+
parent[i] = j;
23+
} else {
24+
parent[j] = i;
25+
if (rank[i] == rank[j]) rank[j]++;
26+
}
27+
--cnt;
28+
}
29+
};

0 commit comments

Comments
 (0)