def shortest_path(self, start: Vertice, destination: Vertice, time: float) -> tuple: for v in self.__v.values(): v.set_distance(-1) v.set_parrent(None) unexplored = MinHeap(len(self.__v)) for v in self.__v.values(): unexplored.insert(v) unexplored.update(start.v_id(), 0) self.__v[start.v_id()].set_distance(0) traffic = 0 for edge in self.__traffic.keys(): for t in self.__traffic[edge]: if time <= t: traffic += 1 v = self.__v[edge[0]] u = self.__v[edge[1]] self.set_e_weight(v, u, self.__weight(v, u, traffic)) traffic = 0 explored = [] while not destination.v_id() in explored: v = unexplored.pop_min() explored.append(v.v_id()) for edge in self.__adj[v.v_id()]: if v.distance() + edge[1] < self.__v[edge[0]].distance(): unexplored.update(edge[0], v.distance() + edge[1]) self.__v[edge[0]].set_distance(v.distance() + edge[1]) self.__v[edge[0]].set_parrent(v) finded_path = [] curr = destination travel_time = 0 while curr is not start: finded_path.append(curr.v_id()) travel_time += self.e_weight(curr, curr.parrent()) curr = curr.parrent() travel_time *= 120 finded_path.append(curr.v_id()) for i in range(len(finded_path) - 1): self.__traffic[(finded_path[i], finded_path[i + 1])].append(time + travel_time) self.__traffic[(finded_path[i + 1], finded_path[i])].append(time + travel_time) finded_path.append(travel_time) return tuple(reversed(finded_path))
def prim(graph: UndirectedGraph): for node in graph.nodes: node.distance = None node.parent = None node.in_queue = True graph.nodes[0].distance = 0 q = MinHeap(graph.nodes, lambda n: n.distance, set_node_distance) while q.get_min(): u = q.pop_min() u.in_queue = False for v in graph.neighbours_of(u): uv_edge = graph.get_edge_between(u, v).weight if v.in_queue and uv_edge < v.distance: v.parent = u v.distance = uv_edge.weight
def prim(graph: UndirectedGraph): for node in graph.nodes: node.distance = None node.parent = None node.in_queue = True graph.nodes[0].distance = 0 q = MinHeap(graph.nodes, lambda n: n.distance, set_node_distance) while q.get_min(): u = q.pop_min() u.in_queue = False for v in graph.neighbours_of(u): uv_edge = graph.get_edge_between(u, v).weight if v.in_queue and uv_edge < v.distance: v.parent = u v.distance = uv_edge.weight
if __name__ == '__main__': sup = MaxHeap([]) # MAX_HEAP inf = MinHeap([]) # MIN_HEAP n = 0 while True: # citesc numarul pe care vreau sa il inserez x = input("Numar: ") x = int(x) sup.insert(x) # inseram in max-heap if n % 2 == 0: if inf.heap_size > 0: # daca am elemente in minheap if sup.max() > inf.min( ): # daca radacina maxHeap-ului > radacina minHeapului # extrag radacinile si le inserez in cruce toMin = sup.pop_max() toMax = inf.pop_min() sup.insert(toMax) inf.insert(toMin) else: # daca numarul de numere e impar toMin = sup.pop_max() inf.insert(toMin) # extrag radacina maxHeap-ului si o inserez in minHeap n += 1 # crestem numarul de elemente procesate # getting the median if n % 2 == 0: print(sup.max() + inf.min()) / 2.0 else: print sup.max()