Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c7d5507

Browse files
Create union_find.cpp
1 parent 2ad5af3 commit c7d5507

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

‎Template/Union_Find/union_find.cpp‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
struct DSU {
2+
vector<int> p, r;
3+
DSU(int n): p(n,-1), r(n,0) {
4+
iota(p.begin(), p.end(), 0);
5+
}
6+
int find(int x) {
7+
return p[x]==x ? x : p[x]=find(p[x]);
8+
}
9+
bool unite(int a, int b) {
10+
a = find(a); b = find(b);
11+
if (a == b) return false;
12+
if (r[a] < r[b]) swap(a,b);
13+
p[b] = a;
14+
if (r[a]==r[b]) ++r[a];
15+
return true;
16+
}
17+
};
18+
19+
int main {
20+
DSU dsu(n);
21+
dsu.unite(u,v);
22+
if (dsu.find(u)==dsu.find(v) {}
23+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /