def __init__(self, graph):

        self.__mst = []
        self.__pq = min_heap.MinHeap(graph.e())
        self.__uf = union_find.UnionFind5(graph.v())

        for i in range(graph.v()):
            adj = graph.adjIterator(graph, i)
            e = adj.begin()
            while not adj.end():
                if e.v() < e.w():
                    self.__pq.insert(e)
                e = adj.next_item()

        while not self.__pq.is_empty() and len(self.__mst) < graph.v() - 1:
            e = self.__pq.extract_min()
            if self.__uf.is_connected(e.v(), e.w()):
                continue

            self.__mst.append(e)
            self.__uf.union(e.v(), e.w())

        self.__mst_weight = self.__mst[0].wt()
        for i in range(1, len(self.__mst)):
            self.__mst_weight += self.__mst[i].wt()
Пример #2
0
def main():
    count = int(input())
    max_heap = maxh.MaxHeap()
    min_heap = minh.MinHeap()

    # put first element in one of the heap
    first = int(input())
    second = int(input())

    if first > second:
        max_heap.insert(second)
        min_heap.insert(first)
    else:
        max_heap.insert(first)
        min_heap.insert(second)

    # set the first median
    print first
    median = (first + second) / 2
    print median
    for i in range(1, count - 1):
        this_num = int(input())
        if this_num < max_heap.peek_max():
            max_heap.insert(this_num)
        else:
            min_heap.insert(this_num)
        balance_heaps(max_heap, min_heap)
        print(get_median(max_heap, min_heap))
Пример #3
0
def dijkstra(G,source=0,trace=False):
    known = [False for i in range(len(G.al))]
    prev = [-1 for i in range(len(G.al))]
    dist =[math.inf for i in range(len(G.al))]
    dist_heap = min_heap.MinHeap()
    dist[source] = 0
    dist_heap.insert(min_heap.HeapRecord(dist[source],source))
    while len(dist_heap.heap)>0:
        heap_node = dist_heap.extractMin()
        v = heap_node.data
        if not known[v]:
            known[v] = True
            for edge in G.al[v]:
                u = edge.dest
                if not known[u]:
                    w = edge.weight
                    if dist[v]+w < dist[u]:
                        prev[u] = v
                        dist[u] = dist[v]+w
                        dist_heap.insert(min_heap.HeapRecord(dist[u],u))
            if trace:
                print('v=',v)
                print('known=',known)
                print('prev=',prev)
                print('dist=',dist)               
    return prev, dist
def prims(graph, start):
    ''' Calculates the minimum spanning tree for a graph and return the minimum cost for the MST '''

    # Initialize all the nodes of the graph as unvisited
    visited = {vertex: False for vertex in graph.adjacency_dict}

    pq = min_heap.MinHeap()
    # Mark the starting node as visited
    visited[start] = True
    # Put the starting node in the mst
    mst = [start]
    minimumCost = 0

    # Insert all the edges from start to min heap
    for edge in graph.adjacency_dict[start]:
        pq.insert(edge)

    while (not all_visited(visited)):

        least_weighted_edge = pq.extract_min()
        # Extract the minimum value until we found one node that is not visited
        while (least_weighted_edge and visited[least_weighted_edge.dest]):
            least_weighted_edge = pq.extract_min()

        if least_weighted_edge:
            visited[least_weighted_edge.dest] = True
            mst.append(least_weighted_edge)
            minimumCost += least_weighted_edge.weight

            # For all the edges connected to the node, we put them in min heap
            for edge in graph.adjacency_dict[least_weighted_edge.dest]:
                pq.insert(edge)

    print minimumCost
Пример #5
0
def prim(G,origin=0, trace=False):
    weight_heap = min_heap.MinHeap()
    connected = set([origin])
    for edge in G.al[origin]:
        weight_heap.insert(min_heap.HeapRecord(edge.weight,[origin,edge.dest,edge.weight]))
    mst = graph.Graph(len(G.al),weighted=True)
    count = 0
    while count<len(G.al)-1 and len(weight_heap.heap)>0:
        next_edge = weight_heap.extractMin().data
        if next_edge[0] not in connected:
            new_vertex = next_edge[0]
        elif next_edge[1] not in connected:
            new_vertex = next_edge[1]  
        else:
            continue
        mst.insert_edge(next_edge[0],next_edge[1],next_edge[2])
        connected.add(new_vertex)
        count+=1
        if trace:
            draw_over(G,mst,'Prim '+str(count))
            print(next_edge,'added to mst')
        for edge in G.al[new_vertex]:
            if edge.dest not in connected:
                weight_heap.insert(min_heap.HeapRecord(edge.weight,[new_vertex,edge.dest,edge.weight]))    
    if count == len(G.al)-1:
        return mst
    print('Graph has no minimum spanning tree')
    return None
Пример #6
0
def dijkstra(G, source):
    pred = {
    }  #Predecessor dictionary. Isn't returned, but here for your understanding
    dist = {}  #Distance dictionary
    Q = min_heap.MinHeap([])
    nodes = list(G.adj.keys())

    #Initialize priority queue/heap and distances
    for node in nodes:
        Q.insert(min_heap.Element(node, 99999))
        dist[node] = 99999
    Q.decrease_key(source, 0)

    #Meat of the algorithm
    while not Q.is_empty():
        current_element = Q.extract_min()
        current_node = current_element.value
        dist[current_node] = current_element.key
        for neighbour in G.adj[current_node]:
            if dist[current_node] + G.w(current_node,
                                        neighbour) < dist[neighbour]:
                Q.decrease_key(
                    neighbour,
                    dist[current_node] + G.w(current_node, neighbour))
                dist[neighbour] = dist[current_node] + G.w(
                    current_node, neighbour)
                pred[neighbour] = current_node
    return dist
Пример #7
0
def kruskal(G,trace=False):
    weight_heap = min_heap.MinHeap()
    S = dsf.DSF(len(G.al))
    for v in range(len(G.al)):
        for edge in G.al[v]:
            if v<edge.dest:
                weight_heap.insert(min_heap.HeapRecord(edge.weight,[v,edge.dest,edge.weight]))
    mst = graph.Graph(len(G.al),weighted=True)
    count = 0
    while count<len(G.al)-1 and len(weight_heap.heap)>0:
        next_edge = weight_heap.extractMin().data
        if S.union(next_edge[0],next_edge[1])==1:
            mst.insert_edge(next_edge[0],next_edge[1],next_edge[2])
            count+=1
            if trace:
                draw_over(G,mst,'Kruskal '+str(count))
                print(next_edge,'added to mst')
        else:
            if trace:
                print(next_edge,'rejected')
        
    if count == len(G.al)-1:
        return mst
    print('Graph has no minimum spanning tree')
    return None
Пример #8
0
    def dijkstra(self):
        self.Q = min_heap.MinHeap([(v, self.d[v]) for v in self.vertices])

        while self.Q.get_length() != 0:
            u = self.Q.extract_min()
            self.S.add(u)

            if u not in self.adj:
                self.adj[u] = set()
            for v in self.adj[u]:
                val = self.relax(u, v)
                if val != False:
                    self.Q.decrease_key(v, val)
Пример #9
0
    def __init__(self, graph):
        self.__g = graph
        self.__pq = min_heap.MinHeap(graph.e())
        self.__marked = [False for _ in range(graph.v())]
        self.__mst = []
        
        self.__visit(0)
#        print(self.__pq.size())
        while not self.__pq.is_empty():
            e = self.__pq.extract_min()
            if self.__marked[e.v()] and self.__marked[e.w()]:
                continue
            
            self.__mst.append(e)
            if not self.__marked[e.v()]:
                self.__visit(e.v())
            else:
                self.__visit(e.w())
                
        self.__mst_weight = self.__mst[0].wt()
        for i in range(1, len(self.__mst)):
            self.__mst_weight += self.__mst[i].wt()
Пример #10
0
    def prims_mst(self):

        self.vertex[0].key = 0

        # inserisco i nodi nella coda
        Q = min_heap.MinHeap()
        for i in self.vertex:
            Q.insert_heap(i)
        Q.heapify(0)

        while Q.heap:

            u = Q.extract_min()
            self.weight += u.key

            if u.parent is not None:
                self.mst.append([u.parent.name, u.name])

            for i in range(0, len(self.vertex)):
                if self.graph[u.name][i] != 0:
                    if self.vertex[i] in Q.heap and self.graph[u.name][i] < Q.heap[Q.heap.index(self.vertex[i])].key:
                        Q.heap[Q.heap.index(self.vertex[i])].parent = u
                        Q.decrease_key(self.vertex[i], self.graph[u.name][i])
Пример #11
0
    print('Question 3')
    
    L = [2,4,6,11,13,3,1,12]
    
    H = htc.HashTableChain(9)
    for i in L:
        H.insert(i)
    H.print_table()
    remove_same_hash(H,1)
    H.print_table()
    remove_same_hash(H,22)
    H.print_table()
    
    print('Question 4')
     
    H = min_heap.MinHeap()
    for i in [4,8,9,14,5,11,7,3,6,10]:
        H.insert(i)
    H.draw()
    for i in range(len(H.heap)+2):
        print(i,sibling(H,i))

    
    print('Question 5')   
    
    A =[11, 6, 7, 16, 17, 2, 4, 18, 14, 8, 15,12]
    TA = bst.BST()
    for a in A:
        TA.insert(a)
    TA.draw()
    
    return False

if __name__=="__main__":
    plt.close('all')
    L0 = [1, 2, 3, 4, 5, 1]
    L1 = [i for i in range(10)]
    L2 = [2302]
    L3 = []
    L4 = [1, 2, 3, 4, 5, 3]
    L5 = [2, 2]
    L6 = [ 2, 2, 1]
    print('-- is_heap')
    for L in [L0,L1,L2,L3,L4,L5,L6]:
        print(is_heap(L))
    
    H1 = min_heap.MinHeap()
    for i in [4,8,2]:
        H1.insert(i)
    H1.draw()
    H2 = min_heap.MinHeap()
    for i in [4,8,9,14,5,7]:
        H2.insert(i)
    H2.draw()
    H3 =  min_heap.MinHeap()
    for i in [4,6,11,8,9,14,5,0,3,7,4]:
        H3.insert(i)
    H3.draw()
    
    H4 =  min_heap.MinHeap()
    for i in [5,0,3,7,8,9,14,4,6,8,9,14,5,6,7,6]:
        H4.insert(i)
Пример #13
0
 def __init__(self):
     super().__init__()
     self.S = set()
     self.Q = min_heap.MinHeap(list())
Пример #14
0
    h = build_index_table(L)
    h.print_table()
    '''
    Table contents:
    bucket 0: [ ]
    bucket 1: [ [1, [3, 6]] ]
    bucket 2: [ [2, [0, 4]] ]
    bucket 3: [ [3, [5]] ]
    bucket 4: [ [4, [1]] [12, [7]] ]
    bucket 5: [ ]
    bucket 6: [ [6, [2]] ]
    bucket 7: [ ]
    '''

    print('Question 4')
    H1 = min_heap.MinHeap()
    for i in [4, 8, 2, 6, 3]:
        H1.insert(i)
    H1.draw()
    H2 = min_heap.MinHeap()
    for i in [4, 8, 9, 14, 5, 7]:
        H2.insert(i)
    H2.draw()

    print(smallest_n(H1, H2, 5))  # [2,3,4,4,5]

    H1 = min_heap.MinHeap()
    for i in [24, 8, 22, 62, 3]:
        H1.insert(i)
    H1.draw()
    H2 = min_heap.MinHeap()
Пример #15
0

def build_tree(heap):
    while not heap.empty():
        left = heap.pop(Cmp().cmp)
        right = heap.pop(Cmp().cmp)
        if left is not None and right is not None:
            heap.insert(Node(left.times + right.times, left, right), Cmp().cmp)
        elif left is None:
            return right
        elif right is None:
            return left


def travel_tree(root, lst, bitstring=''):
    if type(root) == Letter:  # python3 only
        root.bitstring = bitstring
        lst.append(root)
        return
    travel_tree(root.left, lst, bitstring + '0')
    travel_tree(root.right, lst, bitstring + '1')


if __name__ == "__main__":
    heap = min_heap.MinHeap([])
    parser_file(None, heap)
    root = build_tree(heap)
    lst = []
    travel_tree(root, lst, '')
    for one in lst:
        one.dump()