Test instructions
Suppose there are n variables, and a M two-tuple (U, v), which indicates that the variable u is less than V, respectively. So. What should all the variables look like from small to large? For example, there are four variables a,b,c,d, if a < B, C < b, D < C, then these four variables may be ordered a < D < C < b; Although there are other possibilities, you just need to find one.
Ideas:
Consider each variable as a point, and "less than" as an edge, and then get a forward graph. In this way, the actual task is to sort all the nodes of a graph, so that each corresponding to the forward edge (U, v), the corresponding u are in front of the V, that is, topological ordering.
Code:
#include <stdio.h>#include<string.h>#include<iostream>#include<math.h>#include<queue>#include<stack>#include<algorithm>using namespacestd; Const intMAXV = -;intHEAD[MAXV +7];intN, M;queue<int>ansqu;structedgenode{intto ; intNext;} EDGES[MAXV* MAXV +7];intINDEGREE[MAXV];voidGETIDG ()//Get into degrees {memset (Indegree,0,sizeof(Indegree)); for(inti =1; I <= m; i++) indegree[Edges[i].to]++;}voidTplgsort ()//topological sort {getidg (); Stack<int>Tpst; for(inti =1; I <= N; i++) if(!Indegree[i]) Tpst.push (i); while(!Tpst.empty ()) { intv =Tpst.top (); Ansqu.push (v); Tpst.pop (); for(intj = Head[v]; J! =-1; j =edges[j].next)if(! (--indegree[edges[j].to])) Tpst.push (edges[j].to); }}intMain () { while(~SCANF ("%d%d", &n, &m) && (n | |m) {memset (head,-1,sizeof(head)); memset (&edges,0,sizeof(Edgenode)); for(inti =1; I <= m; i++) { intu, v; scanf ("%d%d", &u, &v); Edges[i].to=v; Edges[i].next=Head[u]; Head[u]=i; } tplgsort (); intFlag =0; while(!Ansqu.empty ()) {printf (flag++ ?"%d":"%d", Ansqu.front ()); Ansqu.pop (); } printf ("\ n"); } return 0;}
UVA10305 ordering Tasks (topological sequence)