Stable topological sort

前端 未结 6 981
Happy的楠姐
Happy的楠姐 2020-12-29 04:58

Let say I have a graph where the nodes is stored in a sorted list. I now want to topological sort this graph while keeping the original order where the topological order is

6条回答
  •  旧时难觅i
    2020-12-29 05:02

    Interpreting "stable topological sort" as a linearization of a DAG such that ranges in the linearization where the topological order doesn't matter, are sorted lexicographically. This can be solved with the DFS method of linearization, with the modification that nodes are visited in lexicographical order.

    I have a Python Digraph class with a linearization method which looks like this:

    def linearize_as_needed(self):
        if self.islinearized:
            return
    
        # Algorithm: DFS Topological sort
        # https://en.wikipedia.org/wiki/Topological_sorting#Depth-first_search
    
        temporary = set()
        permanent = set()
    
        L = [ ]
    
        def visit(vertices):
            for vertex in sorted(vertices, reverse=True):
                if vertex in permanent:
                    pass
                elif vertex in temporary:
                    raise NotADAG
                else:
                    temporary.add(vertex)
    
                    if vertex in self.arrows:
                        visit(self.arrows[vertex])
    
                    L.append(vertex)
    
                    temporary.remove(vertex)
                    permanent.add(vertex)
    
            # print('visit: {} => {}'.format(vertices, L))
    
        visit(self.vertices)
        self._linear = list(reversed(L))
        self._iter = iter(self._linear)
        self.islinearized = True
    

    Here

    self.vertices
    

    is the set of all vertices, and

    self.arrows
    

    holds the adjacency relation as a dict of left nodes to sets of right nodes.

提交回复
热议问题