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 011fd1e

Browse files
Create Union Find with Path Compression
1 parent 9a97191 commit 011fd1e

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// Weighted Union Find Algorithm for solving Dynamic Connectivity Problem
2+
#include<bits/stdc++.h>
3+
using namespace std;
4+
#define ll long long int
5+
#define loop(i,N) for(int i=0;i<N;i++)
6+
#define loop_(i,N) for(int i=1;i<=N;i++)
7+
8+
int w[6], id[6];
9+
10+
int root(int node) {
11+
int r = id[node];
12+
while (r != node) {
13+
node = r;
14+
r = id[node];
15+
}
16+
return r;
17+
}
18+
19+
int find(int node) {
20+
return root(node);
21+
}
22+
23+
void quick_union(int i, int j) {
24+
int r1 = root(i);
25+
int r2 = root(j);
26+
if (r1 == r2) {
27+
return;
28+
}
29+
if (w[r1] < w[r2]) {
30+
id[r1] = r2;
31+
w[r2] += w[r1];
32+
}
33+
else {
34+
id[r2] = r1;
35+
w[r1] += w[r2];
36+
}
37+
}
38+
39+
void initialize() {
40+
for (int i = 1; i <= 5; ++i)
41+
{
42+
/* code */
43+
id[i] = i;
44+
w[i] = 1;
45+
}
46+
}
47+
48+
int main() {
49+
initialize();
50+
quick_union(1, 5);
51+
quick_union(2, 3);
52+
quick_union(4, 5);
53+
cout << find(3) << endl;
54+
quick_union(4, 2);
55+
cout << find(3) << endl;
56+
return 0;
57+
}

0 commit comments

Comments
(0)

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