forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.py
59 lines (52 loc) · 1.79 KB
/
1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.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
55
56
57
58
59
class UnionFind:
def __init__(self, n):
self.par = [i for i in range(n)]
self.rank = [1] * n
def find(self, v1):
while v1 != self.par[v1]:
self.par[v1] = self.par[self.par[v1]]
v1 = self.par[v1]
return v1
def union(self, v1, v2):
p1, p2 = self.find(v1), self.find(v2)
if p1 == p2:
return False
if self.rank[p1] > self.rank[p2]:
self.par[p2] = p1
self.rank[p1] += self.rank[p2]
else:
self.par[p1] = p2
self.rank[p2] += self.rank[p1]
return True
class Solution:
def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:
# Time: O(E^2) - UF operations are assumed to be approx O(1)
for i, e in enumerate(edges):
e.append(i) # [v1, v2, weight, original_index]
edges.sort(key=lambda e: e[2])
mst_weight = 0
uf = UnionFind(n)
for v1, v2, w, i in edges:
if uf.union(v1, v2):
mst_weight += w
critical, pseudo = [], []
for n1, n2, e_weight, i in edges:
# Try without curr edge
weight = 0
uf = UnionFind(n)
for v1, v2, w, j in edges:
if i != j and uf.union(v1, v2):
weight += w
if max(uf.rank) != n or weight > mst_weight:
critical.append(i)
continue
# Try with curr edge
uf = UnionFind(n)
uf.union(n1, n2)
weight = e_weight
for v1, v2, w, j in edges:
if uf.union(v1, v2):
weight += w
if weight == mst_weight:
pseudo.append(i)
return [critical, pseudo]