Skip to content

Commit 587e544

Browse files
authored
Created disjoint_set_union.py
Disjoint-Set-Union data structure for python.
1 parent 9629aef commit 587e544

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

disjoint_set_union.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
N = 1000
2+
P = [i for i in range(0,N+1)] # parent
3+
S = [1 for i in range(0,N+1)] # size of set
4+
5+
def find(u):
6+
if u == P[u]:
7+
return u
8+
else:
9+
P[u] = find(P[u])
10+
return P[u]
11+
12+
def union(u,v):
13+
u = find(u)
14+
v = find(v)
15+
if u != v:
16+
# merge smaller set into bigger set
17+
if S[u] < S[v]:
18+
P[u] = v
19+
S[v] += S[u]
20+
else:
21+
P[v] = u
22+
S[u] += S[v]

0 commit comments

Comments
 (0)