请输入您要查询的百科知识:

 

词条 Topological sorting
释义

  1. Examples

  2. Algorithms

     Kahn's algorithm  Depth-first search  Parallel algorithms 

  3. Application to shortest path finding

  4. Uniqueness

  5. Relation to partial orders

  6. See also

  7. References

  8. Further reading

  9. External links

{{Redirect|Dependency resolution|other uses|Dependency (disambiguation)}}

In computer science, a topological sort or topological ordering of a directed graph is a linear ordering of its vertices such that for every directed edge uv from vertex u to vertex v, u comes before v in the ordering. For instance, the vertices of the graph may represent tasks to be performed, and the edges may represent constraints that one task must be performed before another; in this application, a topological ordering is just a valid sequence for the tasks. A topological ordering is possible if and only if the graph has no directed cycles, that is, if it is a directed acyclic graph (DAG). Any DAG has at least one topological ordering, and algorithms are known for constructing a topological ordering of any DAG in linear time.

Examples

The canonical application of topological sorting is in scheduling a sequence of jobs or tasks based on their dependencies. The jobs are represented by vertices, and there is an edge from x to y if job x must be completed before job y can be started (for example, when washing clothes, the washing machine must finish before we put the clothes in the dryer). Then, a topological sort gives an order in which to perform the jobs. A closely related application of topological sorting algorithms was first studied in the early 1960s in the context of the PERT technique for scheduling in project management {{harv|Jarnagin|1960}}; in this application, the vertices of a graph represent the milestones of a project, and the edges represent tasks that must be performed between one milestone and another. Topological sorting forms the basis of linear-time algorithms for finding the critical path of the project, a sequence of milestones and tasks that controls the length of the overall project schedule.

In computer science, applications of this type arise in instruction scheduling, ordering of formula cell evaluation when recomputing formula values in spreadsheets, logic synthesis, determining the order of compilation tasks to perform in makefiles, data serialization, and resolving symbol dependencies in linkers. It is also used to decide in which order to load tables with foreign keys in databases.

The graph shown to the left has many valid topological sorts, including:
  • 5, 7, 3, 11, 8, 2, 9, 10 (visual left-to-right, top-to-bottom)
  • 3, 5, 7, 8, 11, 2, 9, 10 (smallest-numbered available vertex first)
  • 5, 7, 3, 8, 11, 10, 9, 2 (fewest edges first)
  • 7, 5, 11, 3, 10, 8, 9, 2 (largest-numbered available vertex first)
  • 5, 7, 11, 2, 3, 8, 9, 10 (attempting top-to-bottom, left-to-right)
  • 3, 7, 8, 5, 11, 10, 2, 9 (arbitrary)

Algorithms

The usual algorithms for topological sorting have running time linear in the number of nodes plus the number of edges, asymptotically,

Kahn's algorithm

One of these algorithms, first described by {{harvp|Kahn|1962}}, works by choosing vertices in the same order as the eventual topological sort. First, find a list of "start nodes" which have no incoming edges and insert them into a set S; at least one such node must exist in a non-empty acyclic graph. Then:

 L ← Empty list that will contain the sorted elements S ← Set of all nodes with no incoming edge '''while''' S is non-empty '''do'''     remove a node n from S     add n to ''tail'' of L     '''for each''' node m with an edge ''e'' from n to m '''do'''         remove edge e from the graph         '''if''' m has no other incoming edges '''then'''             insert m into S '''if''' graph has edges '''then'''     return error   ''(graph has at least one cycle)'' '''else'''      return L   ''(a topologically sorted order)''

If the graph is a DAG, a solution will be contained in the list L (the solution is not necessarily unique). Otherwise, the graph must have at least one cycle and therefore a topological sorting is impossible.

Reflecting the non-uniqueness of the resulting sort, the structure S can be simply a set or a queue or a stack. Depending on the order that nodes n are removed from set S, a different solution is created. A variation of Kahn's algorithm that breaks ties lexicographically forms a key component of the Coffman–Graham algorithm for parallel scheduling and layered graph drawing.

Depth-first search

An alternative algorithm for topological sorting is based on depth-first search. The algorithm loops through each node of the graph, in an arbitrary order, initiating a depth-first search that terminates when it hits any node that has already been visited since the beginning of the topological sort or the node has no outgoing edges (i.e. a leaf node):

 L ← Empty list that will contain the sorted nodes '''while''' there are unmarked nodes '''do'''     select an unmarked node n     visit(n)  '''function''' visit(node n)     '''if''' n has a permanent mark '''then''' return     '''if''' n has a temporary mark '''then''' stop   ''(not a DAG)''     mark n temporarily     '''for each''' node m with an edge from n to m '''do'''         visit(m)     mark n permanently     add n to ''head'' of L

Each node n gets prepended to the output list L only after considering all other nodes which depend on n (all descendants of n in the graph). Specifically, when the algorithm adds node n, we are guaranteed that all nodes which depend on n are already in the output list L: they were added to L either by the recursive call to visit() which ended before the call to visit n, or by a call to visit() which started even before the call to visit n. Since each edge and node is visited once, the algorithm runs in linear time. This depth-first-search-based algorithm is the one described by {{harvp|Cormen|Leiserson|Rivest|Stein|2001}}; it seems to have been first described in print by {{harvp|Tarjan|1976}}.

Parallel algorithms

On a parallel random-access machine, a topological ordering can be constructed in O(log2 n) time using a polynomial number of processors, putting the problem into the complexity class NC2 {{harv|Cook|1985}}.

One method for doing this is to repeatedly square the adjacency matrix of the given graph, logarithmically many times, using min-plus matrix multiplication with maximization in place of minimization. The resulting matrix describes the longest path distances in the graph. Sorting the vertices by the lengths of their longest incoming paths produces a topological ordering {{harv|Dekel|Nassimi|Sahni|1981}}.

Application to shortest path finding

The topological ordering can also be used to quickly compute shortest paths through a weighted directed acyclic graph. Let {{mvar|V}} be the list of vertices in such a graph, in topological order. Then the following algorithm computes the shortest path from some source vertex {{mvar|s}} to all other vertices:[1]

{{framebox|blue}}
  • Let {{mvar|d}} be an array of the same length as {{mvar|V}}; this will hold the shortest-path distances from {{mvar|s}}. Set {{math|d[s] {{=}} 0}}, all other {{math|d[u] {{=}} ∞}}.
  • Let {{mvar|p}} be an array of the same length as {{mvar|V}}, with all elements initialized to {{mono|nil}}. Each {{math|p[u]}} will hold the predecessor of {{math|u}} in the shortest path from {{mvar|s}} to {{mvar|u}}.
  • Loop over the vertices {{mvar|u}} as ordered in {{mvar|V}}, starting from {{mvar|s}}:
    • For each vertex {{mvar|v}} directly following {{mvar|u}} (i.e., there exists an edge from {{mvar|u}} to {{mvar|v}}):
    • Let {{mvar|w}} be the weight of the edge from {{mvar|u}} to {{mvar|v}}.
    • Relax the edge: if {{math|d[v] > d[u] + w}}, set
    • {{math|d[v] ← d[u] + w}},
    • {{math|p[v] ← u}}.
{{frame-footer}}

On a graph of {{mvar|n}} vertices and {{mvar|m}} edges, this algorithm takes {{math|Θ(n + m)}}, i.e., linear, time.{{r|clrs}}

Uniqueness

If a topological sort has the property that all pairs of consecutive vertices in the sorted order are connected by edges, then these edges form a directed Hamiltonian path in the DAG. If a Hamiltonian path exists, the topological sort order is unique; no other order respects the edges of the path. Conversely, if a topological sort does not form a Hamiltonian path, the DAG will have two or more valid topological orderings, for in this case it is always possible to form a second valid ordering by swapping two consecutive vertices that are not connected by an edge to each other. Therefore, it is possible to test in linear time whether a unique ordering exists, and whether a Hamiltonian path exists, despite the NP-hardness of the Hamiltonian path problem for more general directed graphs {{harv|Vernet|Markenzon|1997}}.

Relation to partial orders

Topological orderings are also closely related to the concept of a linear extension of a partial order in mathematics. In high-level terms, there is an adjunction between directed graphs and partial orders.[2]

A partially ordered set is just a set of objects together with a definition of the "≤" inequality relation, satisfying the axioms of reflexivity (x ≤ x), antisymmetry (if x ≤ y and y ≤ x then x = y) and transitivity (if x ≤ y and y ≤ z, then x ≤ z). A total order is a partial order in which, for every two objects x and y in the set, either x ≤ y or y ≤ x. Total orders are familiar in computer science as the comparison operators needed to perform comparison sorting algorithms. For finite sets, total orders may be identified with linear sequences of objects, where the "≤" relation is true whenever the first object precedes the second object in the order; a comparison sorting algorithm may be used to convert a total order into a sequence in this way. A linear extension of a partial order is a total order that is compatible with it, in the sense that, if x ≤ y in the partial order, then x ≤ y in the total order as well.

One can define a partial ordering from any DAG by letting the set of objects be the vertices of the DAG, and defining x ≤ y to be true, for any two vertices x and y, whenever there exists a directed path from x to y; that is, whenever y is reachable from x. With these definitions, a topological ordering of the DAG is the same thing as a linear extension of this partial order. Conversely, any partial ordering on a finite set may be defined as the reachability relation in a DAG. One way of doing this is to define a DAG that has a vertex for every object in the partially ordered set, and an edge xy for every pair of objects for which x ≤ y. An alternative way of doing this is to use the transitive reduction of the partial ordering; in general, this produces DAGs with fewer edges, but the reachability relation in these DAGs is still the same partial order. By using these constructions, one can use topological ordering algorithms to find linear extensions of partial orders.

See also

  • tsort, a Unix program for topological sorting
  • Feedback arc set, a set of edges whose removal allows the remaining subgraph to be topologically sorted
  • Tarjan's strongly connected components algorithm, an algorithm that gives the topologically sorted list of strongly connected components in a graph
  • pre-topological order

References

1. ^{{Introduction to Algorithms|3|pages=655–657}}
2. ^{{cite book |last1=Spivak |first1=David I.|title=Category Theory for the Sciences |date=2014 |publisher=MIT Press}}
  • {{citation

| last = Cook | first = Stephen A. | authorlink = Stephen Cook
| title = A Taxonomy of Problems with Fast Parallel Algorithms
| journal = Information and Control | volume = 64 | issue = 1–3
| year = 1985 | pages = 2–22
| doi = 10.1016/S0019-9958(85)80041-3}}.
  • {{citation

| last1 = Cormen | first1 = Thomas H. | author1-link = Thomas H. Cormen
| last2 = Leiserson | first2 = Charles E. | author2-link = Charles E. Leiserson
| last3 = Rivest | first3 = Ronald L. | author3-link = Ronald L. Rivest
| last4 = Stein | first4 = Clifford | author4-link = Clifford Stein
| contribution = Section 22.4: Topological sort
| edition = 2nd
| isbn = 0-262-03293-7
| pages = 549–552
| publisher = MIT Press and McGraw-Hill
| title = Introduction to Algorithms
| year = 2001}}.
  • {{citation

| last1 = Dekel | first1 = Eliezer
| last2 = Nassimi | first2 = David
| last3 = Sahni | first3 = Sartaj
| doi = 10.1137/0210049
| issue = 4
| journal = SIAM Journal on Computing
| mr = 635424
| pages = 657–675
| title = Parallel matrix and graph algorithms
| volume = 10
| year = 1981}}.
  • {{citation

| last = Jarnagin | first = M. P.
| title = Automatic machine methods of testing PERT networks for consistency
| year = 1960
| series = Technical Memorandum No. K-24/60
| publisher = U. S. Naval Weapons Laboratory
| location = Dahlgren, Virginia}}.
  • {{citation

| last = Kahn | first = Arthur B.
| title = Topological sorting of large networks
| journal = Communications of the ACM
| volume = 5 | issue = 11 | year = 1962 | pages = 558–562
| doi = 10.1145/368996.369025}}.
  • {{citation

| last = Tarjan | first = Robert E. | authorlink = Robert Tarjan
| title = Edge-disjoint spanning trees and depth-first search
| journal = Acta Informatica | volume = 6 | issue = 2 | year = 1976 | pages = 171–185
| doi = 10.1007/BF00268499}}.
  • {{citation

| last1 = Vernet | first1 = Oswaldo
| last2 = Markenzon | first2 = Lilian
| contribution = Hamiltonian problems for reducible flowgraphs
| title = Proc. 17th International Conference of the Chilean Computer Science Society (SCCC '97)
| year = 1997
| pages = 264–267
| doi = 10.1109/SCCC.1997.637099}}.

Further reading

  • D. E. Knuth, The Art of Computer Programming, Volume 1, section 2.2.3, which gives an algorithm for topological sorting of a partial ordering, and a brief history.

External links

  • [https://xlinux.nist.gov/dads/HTML/topologicalSort.html NIST Dictionary of Algorithms and Data Structures: topological sort]
  • {{MathWorld|urlname=TopologicalSort|title=TopologicalSort}}
{{sorting}}

4 : Graph algorithms|Sorting algorithms|Directed graphs|Articles with example pseudocode

随便看

 

开放百科全书收录14589846条英语、德语、日语等多语种百科知识,基本涵盖了大多数领域的百科知识,是一部内容自由、开放的电子版国际百科全书。

 

Copyright © 2023 OENC.NET All Rights Reserved
京ICP备2021023879号 更新时间:2024/9/24 7:23:11