1. Definition
Topological ordering of a direction-free graph G is a linear sequence of all vertices in g, usually such a linear sequence is called a sequence that satisfies the topological order (topological order), or a topological sequence.
Example:
when we get up and wear pants and shoes, I believe most people are in the order that they put on their underwear, then put on their pants, put on their socks, and then the shoes. So , Let's break down these steps:
(1) wear underwear
(2) wear pants
(3) wear Socks
(4) wear Shoes
Let's take these four steps and arrange them in the order described above. , is the so-called topological sort.
2. Note
1) A topological sequence exists only in the direction-free graph;
2) for a DAG, there may be multiple topological sequences;
Such as:
The topology sequence for the DAG is a B c D or a C b d
There is no topological sequence for this graph, as there are loops in the diagram
3. Topology Sequence algorithm idea
(1) Selecting a vertex with no precursor (i.e., 0) from the graph, and outputting it;
(2) Delete this vertex and all arcs with its tail from the graph;
Repeat the above two steps until the diagram is empty, or the diagram is not empty but cannot find a vertex without a precursor. 4. Code
#include <cstdio>#include<cstring>intans[510][510];//to record whether the two men had a match.intn,indegree[510];//record the number of precursorsintqueue[510];//Save TopologyvoidTopsort () {inti,j,top,k=0; for(j=0; j<n; ++j) { for(i=1; i<=n; ++i) {if(indegree[i]==0)//The precursor is zero, which is the current first place .{Top=i; Break; }} queue[k++]=top;//the current first name into the queue, can also be directly outputindegree[top]=-1;//The number of precursors is updated to-1 to avoid repeating the queue for(i=1; i<=n; ++i) {if(Ans[top][i])//reduce the number of precursors that contain the current first name to oneindegree[i]--; } } for(i=0; i<k-1; ++i) printf ("%d", Queue[i]); printf ("%d\n", queue[n-1]);}intMain () {inti,a,b,m; while(SCANF ("%d%d", &n,&m)! =EOF) {memset (Indegree,0,sizeof(Indegree));//array initialized to 0memset (ans,0,sizeof(ans));//array initialized to 0 for(i=0; i<m; ++i) {scanf ("%d%d",&a,&b); if(ans[a][b]==0) {Ans[a][b]=1;//record whether the contest was conductedindegree[b]++;//record number of precursors}} topsort (); } return 0;}
Topological sort Topsort Detailed