File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution :
2+ class DSU :
3+ def __init__ (self , n : int ):
4+ self .parents = list (range (n ))
5+ self .ranks = [0 ] * n
6+
7+ def find (self , u : int ) -> int :
8+ if u == self .parents [u ]:
9+ return u
10+
11+ self .parents [u ] = self .find (self .parents [u ])
12+ return self .parents [u ]
13+
14+ def union (self , u : int , v : int ):
15+ pU , pV = self .find (u ), self .find (v )
16+
17+ if pU == pV :
18+ return
19+
20+ if self .ranks [pU ] < self .ranks [pV ]:
21+ self .parents [pU ] = pV
22+ elif self .ranks [pV ] < self .ranks [pU ]:
23+ self .parents [pV ] = pU
24+ else :
25+ self .parents [pU ] = pV
26+ self .ranks [pV ] += 1
27+
28+ def spanningTree (self , V : int , edges : list [list [int ]]) -> int :
29+ dsu = self .DSU (V )
30+
31+ # sort by weights in ascending order
32+ edges .sort (key = lambda x : x [2 ])
33+ mst = 0
34+
35+ for u , v , weight in edges :
36+ # if both are in different components union them
37+ if dsu .find (u ) != dsu .find (v ):
38+ dsu .union (u , v )
39+ mst += weight
40+
41+ return mst
You can’t perform that action at this time.
0 commit comments