Esempio n. 1
0
File: mst.py Progetto: storypku/tlpi
def MST_Kruskal(g):
    """Compute a minimum spanning tree of a simple connected weighted graph g
    using Kruskal's algorithm.

    Return a list of edges that comprise the MST.
    """
    tree = []                   # list of edges in spanning tree
    pq = HeapPriorityQueue()    # entries are edges in g, with weights as key
    forest = Partition()        # keeps track of forest clusters
    position = {}               # map each node to its Partition entry

    for v in g.vertices():
        position[v] = forest.make_group(v)
    for e in g.edges():
        pq.add(e.element(), e)  # edge's element is assumed to be its weight

    size = g.vertex_count()
    while len(tree) != size - 1 and not pq.is_empty():
        # tree not spanning and unprocessed remain
        weight, edge = pq.remove_min()
        u, v = edge.endpoints()
        a = forest.find(position[u])
        b = forest.find(position[v])
        if a != b:
            tree.append(edge)
            forest.union(a, b)

    return tree
Esempio n. 2
0
def MST_Kruskal(g):
    """Compute a minimum spanning tree of a simple connected weighted graph g
    using Kruskal's algorithm.

    Return a list of edges that comprise the MST.
    """
    tree = []  # list of edges in spanning tree
    pq = HeapPriorityQueue()  # entries are edges in g, with weights as key
    forest = Partition()  # keeps track of forest clusters
    position = {}  # map each node to its Partition entry

    for v in g.vertices():
        position[v] = forest.make_group(v)
    for e in g.edges():
        pq.add(e.element(), e)  # edge's element is assumed to be its weight

    size = g.vertex_count()
    while len(tree) != size - 1 and not pq.is_empty():
        # tree not spanning and unprocessed remain
        weight, edge = pq.remove_min()
        u, v = edge.endpoints()
        a = forest.find(position[u])
        b = forest.find(position[v])
        if a != b:
            tree.append(edge)
            forest.union(a, b)

    return tree
Esempio n. 3
0
    def _compose_ht_tree(self, text):
        """Huffman tree construction for text."""
        freq_table = self._compute_chr_freq(text)
        ht_queue = HeapPriorityQueue()
        for freq, lett in freq_table:
            ht_tree = LinkedBinaryTree()
            ht_tree._add_root((freq, lett))
            ht_queue.add(freq, ht_tree)

        while len(ht_queue) > 1:
            (freq1, subtree1) = ht_queue.remove_min()
            (freq2, subtree2) = ht_queue.remove_min()
            freq = freq1 + freq2
            ht_tree = LinkedBinaryTree()
            ht_tree._add_root((freq, None))
            ht_tree._attach(ht_tree.root(), subtree1, subtree2)
            ht_queue.add(freq, ht_tree)
        _, ht_tree = ht_queue.remove_min()
        return ht_tree