-
Notifications
You must be signed in to change notification settings - Fork 0
/
union.py
54 lines (43 loc) · 1.44 KB
/
union.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# 354. Russian Doll Envelopes
# 952. Largest Component Size by Common Factor
# 684. Redundant Connection
# 685. Redundant Connection II
# Disjoint union set is a data structure that tracks a set of data partitioned in a number of non-overlapping subsets.
# The data structure supports find (locate the subset for a given data) and union (combine two subsets) operations.
# optional: Union-by-rank: determine how two subsets are unioned based on their ranks.
class DSU:
def __init__(self, nodes):
self.par = list(range(nodes))
def find(self, x):
if self.par[x] != x:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
self.par[self.find(x)] = self.find(y)
'''
class DSU:
def __init__(self, nodes):
self.par = list(range(nodes))
self.rnk = [0] * nodes
def find(self, x):
if self.par[x] != x:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
xr, yr = self.find(x), self.find(y)
if xr == yr:
return False
elif self.rnk[xr] < self.rnk[yr]:
self.par[xr] = yr
elif self.rnk[xr] > self.rnk[yr]:
self.par[yr] = xr
else:
self.par[yr] = xr
self.rnk[xr] += 1
return True
'''
class Solution:
def yourfunction(self, data):
dsu = DSU(len(data))
dsu.union(x,y)
print(dsu.par)