def TestDagShortestPathsModified(self): u = Vertex('u') v = Vertex('v') w = Vertex('w') z = Vertex('z') u.weight = 1 v.weight = 2 w.weight = 3 z.weight = 4 vertices = [u, v, w, z] edges = [(u, v), (v, w), (v, z)] G = Graph(vertices, edges) self.assertEqual(dag_shortest_paths_modified(G, u), [u, v, z])
def TestDagShortestPathsModified(self): u = Vertex('u') v = Vertex('v') w = Vertex('w') z = Vertex('z') u.weight = 1 v.weight = 2 w.weight = 3 z.weight = 4 vertices = [u, v, w, z] edges = [(u, v), (v, w), (v, z)] G = Graph(vertices, edges) self.assertEquals(dag_shortest_paths_modified(G, u), [u, v, z])
def shift(vertex: Vertex, num_vertices: int) -> Vertex: """ Returns the Vertex that is the root for this tree :param vertex: the vertex we want to shift :param num_vertices: the number of vertices in the graph [invariant] :return: """ # If no neighbour of u has weight > neighbour.weight/2, return u result = vertex for neighbour in vertex.neighbours: if neighbour.weight > num_vertices / 2: vertex.weight = vertex.weight - neighbour.weight neighbour.weight = vertex.weight + neighbour.weight result = shift(neighbour, num_vertices) return result
def set_weight(root: Vertex, parent: Vertex = None): """ Recursively assigns weights to the induced subgraphs starting with the root :param root: Vertex :param parent: The parent of the root, because those do not count in the weight of a subgraph :return: """ if root.degree == 1 and root.neighbours[0] == parent: root.weight = 1 return 1 else: for neighbour in root.neighbours: if neighbour != parent: root.weight += set_weight(root=neighbour, parent=root) root.weight += 1 return root.weight