예제 #1
0
 def main_1(grp):
     edge = []
     for i in range(len(grp)):
         for j, w in grp[i]:
             m, n = min(i, j), max(i, j)
             if (m, n, w) not in edge:
                 edge.append((m, n, w))
     assert (len(edge) == sum(map(len, grp)) / 2)
     edge.sort(key=lambda x: x[2])
     ret = []
     ds = DisjointSetForest(len(grp))
     for i, j, w in edge:
         if ds.find(i) != ds.find(j):
             ret.append(w)
             ds.union(i, j)
     assert (len(ret) == len(grp) - 1)
     return sum(ret)
예제 #2
0
 def main_Kruskal(self, grp, src=None):
     # 1) build array of edges and sort
     edge = []
     for i in range(len(grp)):
         for j, w in grp[i]:
             m, n = min(i, j), max(i, j)
             if ((m, n), w) not in edge:
                 edge.append(((m, n), w))
     assert (len(edge) == sum(map(len, grp)) / 2)
     edge.sort(key=lambda x: x[1])
     # 2) build MST by greedily selecting edges
     mst = []
     ds = DisjointSetForest(len(grp))
     for (i, j), w in edge:
         if ds.find(i) != ds.find(j):
             ds.union(i, j)
             mst.append(((i, j), w))
     assert (len(mst) == len(grp) - 1)
     return mst
예제 #3
0
 def main_1(grp):
     edge = []
     for i in range(len(grp)):
         for j, w in grp[i]:
             m, n = min(i, j), max(i, j)
             if (m, n, w) not in edge:
                 edge.append((m, n, w))
     assert (len(edge) == sum(map(len, grp)) / 2)
     edge.sort(key=lambda x: x[2])
     ret = []
     ds = DisjointSetForest(len(grp))
     for i, j, w in edge:
         if ds.find(i) != ds.find(j):
             ret.append(w)
             ds.union(i, j)
     assert (len(ret) == len(grp) - 1)
     return sum(ret)