kruskal算法模板python
作者:
endinggy
,
2021-06-11 03:34:21
,
所有人可见
,
阅读 381
class UNSET():
def __init__(self, n):
self.n = n
self.pre = list(range(n))
def find(self, i):
if i != self.pre[i]: self.pre[i] = self.find(self.pre[i])
return self.pre[i]
def un(self, i, j):
fi, fj = self.find(i), self.find(j)
if fi != fj:
self.pre[fi] = fj
def kruskal(n, e):
from heapq import heappop, heappush
us = UNSET(n)
q = []
for u in range(n):
for d, v in e[u]: q.append([d, u, v])
q.sort()
res = 0
for d, u, v in q:
fu, fv = us.find(u), us.find(v)
if fu != fv: res += d; us.un(u, v)
return res