classUnionFind:def__init__(self, n):
self.parent =list(range(n))
self.cnt = n # 连通块个数deffind(self, a):
acopy = a
while a != self.parent[a]:
a = self.parent[a]while acopy != a:
self.parent[acopy], acopy = a, self.parent[acopy]return a
defmerge(self, a, b):# 这是一个无用的合并if self.find(b)== self.find(a):returnFalse# 这是一个有用的合并
self.parent[self.find(b)]= self.find(a)
self.cnt -=1returnTrueclassSolution:defmaxNumEdgesToRemove(self, n:int, edges: List[List[int]])->int:# edges预处理为[0, n - 1]for i inrange(len(edges)):
edges[i][1]-=1
edges[i][2]-=1# 加入两个并查集
ufa, ufb = UnionFind(n), UnionFind(n)# 记录删除无用边的总个数
ans =0# 先看公共边for t, u, v in edges:if t ==3:
flag1 = ufa.merge(u, v)
flag2 = ufb.merge(u, v)# 都没有用才不要这个公共边# 否则它的贡献至少是独有边ifnot flag1 andnot flag2:
ans +=1else:pass# 再看单独边for t, u, v in edges:if t ==1:ifnot ufa.merge(u, v):
ans +=1elif t ==2:ifnot ufb.merge(u, v):
ans +=1#print(ufa.parent)#print(ufb.parent)if ufa.cnt !=1or ufb.cnt !=1:return-1return ans