Skip to main content

1579. Remove Max Number of Edges to Keep Graph Fully Traversable

class Solution1:
def maxNumEdgesToRemove(self, n: int, edges: list[list[int]]) -> int:
class UF:
def __init__(self, n: int):
self.root = list(range(n))
self.groups = n

def find(self, x: int):
if self.root[x] != x:
self.root[x] = self.find(self.root[x])
return self.root[x]

def union(self, x: int, y: int):
x_root, y_root = self.find(x), self.find(y)
result = int(x_root != y_root)
if result:
self.root[x_root] = y_root
self.groups -= 1
return result

ufs = [UF(n), UF(n)]
result = 0
for t, u, v in sorted(edges, reverse=True):
r = 1
for i in range(len(ufs) - 1, -1, -1):
if t > i:
r &= ufs[i].union(u - 1, v - 1)
t -= i + 1
result += r ^ 1 # 1, 0 -> 0, 1
return result if ufs[0].groups == ufs[1].groups == 1 else -1


class Solution:
def maxNumEdgesToRemove(self, n: int, edges: list[list[int]]) -> int:
def union(root, x: int, y: int):
def find(x: int):
if root[x] != x:
root[x] = find(root[x])
return root[x]

x_root, y_root = find(x), find(y)
result = int(x_root != y_root)
if result:
root[x_root] = y_root
return result

roots = [list(range(n)), list(range(n))]
groups = [n, n]
result = 0
for t, u, v in sorted(edges, reverse=True):
r = 1
for i in range(len(groups) - 1, -1, -1):
if t > i:
uni = union(roots[i], u - 1, v - 1)
if uni:
groups[i] -= 1
r &= uni
t -= i + 1
result += r ^ 1 # 1, 0 -> 0, 1
return result if all(x == 1 for x in groups) else -1