コード例 #1
0
ファイル: kruskal.py プロジェクト: z821402562/aucs-dsa
def kruskal():
    A = []
    ds = DisjointSets(V)  # make set
    for e in elist:
        u = e.u
        v = e.v
        if ds.findset(u) != ds.findset(v):
            A.append(e)
            ds.union(u, v)
    return A
コード例 #2
0
def main():
    ''' Adjacency List representation. G is a list of lists. '''
    G = []
    V = []
    E = set()
    T = set()
    id = 0

    ds = DisjointSets()

    file = open('input.txt', 'r')
    for line in file:
        line = line.strip()
        adjacentVertices = []
        first = True
        for edge in line.split(' '):
            if first:
                first = False
                continue
            node, weight = edge.split(',')
            adjacentVertices.append((int(node), int(weight)))
            E.add((frozenset([id, int(node)]), int(weight)))
        G.append(adjacentVertices)
        id += 1

    file.close()

    E = sorted(E, key=lambda x: x[1])

    for i in range(len(G)):
        v = ds.makeset(i)
        V.append(v)

    for edge in E:
        [a, b] = edge[0]
        if len(T) == len(G) - 1:
            break
        if ds.findset(V[a]) != ds.findset(V[b]):
            T.add(edge[0])
            ds.union(V[a], V[b])

    print("The edges in the minimum spanning tree are:")
    for edge in T:
        [a, b] = edge
        print(a, b)
コード例 #3
0
ファイル: kruskal.py プロジェクト: Sujan242/DSA2
def kruskal(G):

    G=sorted(G)
    # print(G)
    ds = DisjointSets()
    
    nodes = []
    for i in range(len(G)):
        node = ds.makeset(i)
        nodes.append(node)


    wt=0
    for w,u,v in G:

        if ds.findset(nodes[u]) != ds.findset(nodes[v]):
            wt+=w
            ds.union(nodes[u],nodes[v])
    print(wt)
コード例 #4
0
    def mst_kruskal(self):
        """Returns the set of edges in some
        minimum spanning tree (MST) of the graph,
        computed using Kruskal's algorithm.
        """

        A = set()
        forest = DisjointSets(len(self._adj))
        edges = self.get_edge_list(True)
        edges.sort(key=lambda x: x[1])
        for e, w in edges:
            if forest.find_set(e[0]) != forest.find_set(e[1]):
                A.add(e)
                # A = A | {e}
                forest.union(e[0], e[1])
        return A
コード例 #5
0
def init_ds(size):
    ds = DisjointSets()
    for i in range(size):
        ds.make_set(i)
    return ds