Algorithm and data structure basics 10: C ++ implementation-topological sorting

Source: Internet
Author: User

Algorithm and data structure basics 10: C ++ implementation-topological sorting
1. Defining topological sorting is a sort of Directed Acyclic Graph (DAG) vertices,
It causes A path from vertex A to vertex B to appear after vertex A in the order.


Two prerequisites: directed, acyclic, or directed acyclic graph.


Three-partial-order full-order connected graph: at least one edge exists between any two points.
Partial Order: non-connected graph (directed acyclic graph satisfies Partial Order)
Full Order: Single-Connected Graph


The uniqueness of the result is not unique in a directed acyclic graph that only satisfies the partial order relationship, because the relationship between two vertices is uncertain.
A directed acyclic graph that satisfies the full-order relationship. Two vertices have directed edges, so the sorting result is unique.


Five-level sorting each step of the method always outputs the vertex with no forward direction (that is, the inbound degree is zero) and outputs the "topological order ".
The abstract algorithm can be described as follows:
NonPreFirstTopSort (G) {// preferentially outputs vertices without a forward trend
While (G contains vertices with an inbound degree of 0) do {
Select a vertex v whose input degree is 0 from G and output it;
Delete v and all outbound edges from G;
}
If (number of output vertices <| V (G) |) // if this condition is not true, all vertices are output and sorted successfully.
Error ("G contains a directed ring. Sorting failed! ");
}
Note:
Topology Sorting algorithms with no forward direction are stored in a specific storage structure. To facilitate the investigation of the inbound degree of each vertex, the current inbound degree of each vertex can be saved.
To avoid scanning the entire bucket every time you select a vertex with an input of 0, you can set a stack or a queue to store all vertices with zero input:
Before sorting, scan the corresponding storage space and add the vertices with zero inbound to the stack (Team ). In the future, you only need to perform the stack (Team) operation each time you select the vertex with the input degree of 0.


Each step of this method is to output the vertex with no successor (that is, the outbound degree is 0), and the output is "inverse topological order ".
The abstract description of the algorithm is:
NonSuccFirstTopSort (G) {// preferentially outputs vertex without successor
While (G has a vertex with an outbound degree of 0) do {
Select a vertex v with a degree of 0 from G and output v;
Delete all input edges of v and v from G.
}
If (number of output vertices <| V (G) |)
Error ("G contains a directed ring. Sorting failed! ");
}




7. Depth first when the DFS search from a vertex v is completed, all the successors of v must have been accessed (imagine they have been deleted ),
At this time, v is equivalent to no subsequent vertex. Therefore, the reverse topology sequence of the DAG can be obtained by outputting the vertex v before the DFS algorithm returns.
The first output vertex must be a vertex without any successor (with an outbound degree of 0). It should be the last vertex of the topological sequence.
If you do not want to obtain an inverse topological sequence, you can add T to save the output vertex. If T is a stack and T is initialized at the beginning of the DFSTraverse algorithm,
The abstract algorithm that uses DFS to calculate the topological sequence can be described as follows:
Void DFSTopSort (G, I, T ){
// Call this algorithm in DisTraverse. I is the starting point of search and T is the stack.
Int j;
Visited [I] = TRUE; // access I
For (neighbor j of all I) // that is ε E (G)
If (! Visited [j])
DFSTopSort (G, j, T );
// The preceding statement is similar to the DFS algorithm.
Push (& T, I); // the search from I has been completed, and the output I

}



The eight codes only implement the degree of exit, and the other two are similar and are not written.

// GraphList. h (based on the code in this article, the algorithm and data structure are modified. 8: C ++ implements directed graph-adjacent table Storage)

# Include
 
  
# Include
  
   
# Include
   
    
# Include
    
     
Using namespace std; // Edge struct Edge {int vName; int weight; // weight struct Edge * next ;}; // Vertex (linked list header) struct Vertex {int vName; int in; // inbound int out; // struct Edge * next;}; // directed graph class GraphList {public :~ GraphList (); void createGraph (); void printGraph (); bool topsortInDegree (); bool topsortOutDegree (); private: // 1. enter the number of void inputVertexCount (); // 2. generate a fixed-point array void makeVertexArray (); // 3. enter the number of sides void inputEdgeCount (); // 4. start Point of the input edge void inputEdgeInfo (); // 5. add edge nodes to the corresponding linked list. void addEdgeToList (int vFrom, int weight, int vTo); private: int m_vCount; int m_eCount; Vertex * m_vVertex ;}; GraphList ::~ GraphList () {for (int I = 0; I <m_vCount; ++ I) {Edge * tmp = m_vVertex [I]. next; Edge * edge = NULL; while (tmp) {edge = tmp; tmp = tmp-> next; delete edge; edge = NULL ;}} delete [] m_vVertex ;} void GraphList: inputVertexCount () {cout <"please input count of vertex:"; cin >>m_vcount;} void GraphList: makeVertexArray () {m_vVertex = new Vertex [m_vCount]; // initialize for (int I = 0; I <m_vCount; ++ I) {m_vVertex [I]. vName = I; m_vVertex [I]. next = NULL; m_vVertex [I]. in = 0; m_vVertex [I]. out = 0 ;}} void GraphList: inputEdgeCount () {cout <"please input count of edge:"; cin >>m_ecount;} void GraphList: inputEdgeInfo () {cout <"please input edge information:" <endl; for (int I = 0; I <m_eCount; ++ I) {cout <"the edge" <I <":" <endl; // start point int from = 0; cout <"From :"; cin> from; // weight int Weight = 0; cout <"weight:"; cin> weight; // end point int to = 0; cout <"To:"; cin> to; cout <endl; addEdgeToList (from, weight, to) ;}} void GraphList: addEdgeToList (int vFrom, int weight, int vTo) {Edge * edge = new Edge (); edge-> vName = vTo; edge-> weight = weight; edge-> next = NULL; edge * tmp = m_vVertex [vFrom]. next; if (tmp) {while (tmp-> next) {tmp = tmp-> next;} tmp-> next = edge;} else {m_vVertex [vFrom]. next = edge;} ++ m_vVertex [vTo]. in; // Add 1 + m_vVertex [vFrom] to the end. out; // Add 1} void GraphList: printGraph () {for (int I = 0; I <m_vCount; ++ I) {Edge * tmp = m_vVertex [I]. next; cout <"list:" <m_vVertex [I]. vName <"(in:" <m_vVertex [I]. in <")" <"->"; while (tmp) {cout <"(weight:" <tmp-> weight <")"; cout <tmp-> vName <"->"; tmp = tmp-> next;} cout <"NULL" <endl ;}} bool GraphList :: topsortInDegree () {stack
     
      
VertexStack; queue
      
        VertexQueue; int * degree = new int [m_vCount]; // declare a temporary variable, save the inbound value, and perform the operation, avoid affecting the data in the original node. // for (int I = 0; I <m_vCount; ++ I) {degree [I] = m_vVertex [I]. in; if (! Degree [I]) {vertexStack. push (& m_vVertex [I]) ;}} int count = 0; while (! VertexStack. empty () {// save Vertex * tmp = vertexStack. top (); vertexStack. pop (); vertexQueue. push (tmp); ++ count; // 2 Delete the node and all its outbound edges (that is, the inbound degree of the adjacent vertex minus 1) Edge * edge = tmp-> next; while (edge) {Vertex * vertex = & m_vVertex [edge-> vName]; -- degree [edge-> vName]; if (! Degree [edge-> vName]) {vertexStack. push (vertex) ;}edge = edge-> next ;}// determine whether there is a ring if (count <m_vCount) {return false ;}// output the sorting result while (! VertexQueue. empty () {Vertex * tmp = vertexQueue. front (); vertexQueue. pop (); cout <tmp-> vName <"" ;}cout <endl; delete [] degree; return true ;} //************************************** * ********************************** // Process Control //************************************** *********************************** void GraphList:: createGraph () {inputVertexCount (); makeVertexArray (); inputEdgeCount (); inputEdgeInfo ();}
      
     
    
   
  
 



// Main. cpp

// test for GraphList#include "GraphList.h"#include 
 
  int main(){GraphList graph;graph.createGraph();graph.printGraph();graph.topsort();system("pause");return 0;}
 


Assume that the following figure is shown: (the first two sections are used)



Result:








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.