Topological sequencing-graph theory

Source: Internet
Author: User
Tags in degrees

If we have a set of tasks to complete, and some of the other tasks of the talent end after the start. Therefore, we must be very careful about the order in which these tasks are run.


Assuming these tasks are very simple to run the order of the words, we can use them to store the list, which is a very good scheme so that we can know the full task of running the order.

The relationship between the two is very complex. Some tasks depend on two or even many other tasks, or in turn very many tasks depend on themselves.


Therefore, we cannot model this problem through the data structure of a linked list or tree. The only logical data structure for this kind of problem is the graph. What kind of chart do we need? Obviously, we need to have a diagram to describe such a relationship, and is not a circular graph, we call it a direction-free graph. To sort the graphs by topological sorting, the graphs must not be circular and forward.

Why can't these graphs loop? The answer is very obvious, assuming the graph is circular. We have no way of knowing which task should run first, or sort the task. Now all we have to do is sort each of the nodes in the diagram. form a strip of edges (U. V). U runs before v.

Then we can get the linear order of all the tasks. and run the task in this order, everything is OK.

For example, a topological sort of the following figure is "5 4 2 3 1 0". A graph can have multiple topological sorts.


There is also a topological sort of "4 5 2 3 1 0". The first vertex of a topological sort is always in the degree of 0.

Method One
Now we can get the basic steps of this algorithm:

1. Construct the empty list L and s;2. Put all nodes that are not dependent on the node (0 in degrees) into l;3. When L has a node, run the following steps: 3.1     L take out a node n (remove from L), and put S3.2         on each neighboring n node m, 3.2.1           removes the Edge (n,m), (indicates an increase in the finally result set s) 3.2.2           assumes m has no dependent node (in degrees 0), put M into L;

The core is: each time you select a node with a degree of 0, and then update its neighboring nodes of the degree.

This is a relatively straightforward algorithm, but also a common algorithm. We use an array of degree[] to record the degrees of all vertices.

The array is updated when the point is deleted.
Refer to the following code functions: TopologicalSort1 ()

Method Two
The second method is to refer to DFS and make some changes to the graph's depth-first traversal.

We are sure that there is an edge (U,V) in the forward graph, then the vertex u enters the list before the vertex v. Therefore, in the deep traversal, the stack is used to store the traversal order. The function of the following code: TOPOLOGICALSORT2 ()

C + + implementation

Topology sorting algorithm implemented by C + + #include<iostream> #include <list> #include <stack>using namespace std;//Graph class    graph{int V;    Vertex number//adjacency table list<int> *adj; Topological sorting Method 2 auxiliary function void Topologicalsortrecall (int V, BOOL visited[], stack<int> &stack);p ublic:graph (int v)     ;    Added edge void Addedge (int v, int w);    Topological ordering general method void TopologicalSort1 (); Topological sorting Method two void TopologicalSort2 ();};    graph::graph (int V) {this->v = V; Adj = new List<int>[v];} void Graph::addedge (int v, int w) {adj[v].push_back (w);//}//similar depth first traversal.    Place the vertex adjacent to V (and for the interview) in the stack void graph::topologicalsortrecall (int V, BOOL visited[], stack<int> &stk) {//Mark V for interview    VISITED[V] = true;    Recursive invocation of List<int>::iterator I for each vertex; for (i = Adj[v].begin (); I! = Adj[v].end (); ++i) if (!visited[*i]) Topologicalsortrecall (*i, visited, St    k); Save Vertex Stk.push (v);}  Method Two, use recursive call to implement topological sort void graph::topologicalsort2 () {stack<int> stk;  BOOL *visited = new BOOL[V];    for (int i = 0; i < V; i++) visited[i] = false; Each vertex is called once for (int i = 0; i < V; i++) if (visited[i] = = False) Topologicalsortrecall (I, visited, Stk)    ;        Print while (stk.empty () = = False) {cout << stk.top () << "";    Stk.pop (); }}//method one void Graph::topologicalsort1 () {list<int>::iterator j;int degree[v];//traverses all edges, calculates the in-degree for (int i=0; i<v; i+ +) {Degree[i] = 0;for (j = Adj[i].begin (); J! = Adj[i].end (); ++j) {degree[*j]++;}} list<int> zeronodes;//all degrees 0 points list<int> result;//the point for which all degrees are 0 (int i=0; i<v; i++) {if (degree[i] = = 0) { Zeronodes.push_back (i);}} while (Zeronodes.size () > 0) {int top = Zeronodes.back (), Zeronodes.pop_back (); Result.push_back (top); for (j = Adj[top] . Begin (); J! = Adj[top].end (); ++J) {degree[*j]--;//Delete and top adjacent edges, and update the other vertex's in degrees if (degree[*j] = 0) zeronodes.push_back (*j);}} Print the results for (j= Result.begin (); J! = Result.end (), j + +) cout << (*j) << "";} int main () {    Create the graph graph G (6) in the text;    G.addedge (5, 2);    G.addedge (5, 0);    G.addedge (4, 0);    G.addedge (4, 1);    G.addedge (2, 3);    G.addedge (3, 1);    cout << "Following is a topological Sort of the given graph using topologicalsort1\n";    G.topologicalsort1 ();    cout << Endl;    cout << "Following is a topological Sort of the given graph using topologicalsort2\n";    G.topologicalsort2 (); return 0;}

Reference: http://www.geeksforgeeks.org/topological-sorting/


Topological sequencing-graph theory

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.