Ordering TasksInput:standard inputoutput:standard outputtime limit:1 secondmemory limit:32 MB
John had n tasks to do. Unfortunately, the tasks independent and the execution of one task is only possible if and tasks with already be En executed.
Input
The input would consist of several instances of the problem. Each instance begins with a line containing the integers, 1 <= n <= and M. N is the number of the tasks (numbered FR Om 1 to N) and M are the number of direct precedence relations between tasks. After this, there would be m lines with II integers I and J, representing the fact that task I must be executed before TAS K J. An instance with n = m = 0 would finish the input.
Output
For each instance, print a line with n integers representing the tasks in a possible order of execution.
Sample Input
5 4
1 2
2 3
1 3
1 5
0 0
Sample Output
1 4 2) 5 3
(The Joint Effort Contest, problem Setter:rodrigo Malta Schmidt)
The main topic: There are n variables, and m two-tuple relationship. The relationship (x, y) represents X<y. Now tell all the variables
From small to large to sort, to output.
For example: There are 4 variables a, B, C, D, if a<b,c<b,d<c, then the sort may be a<d<c<b,
There are other possible d<a<c<d. Just enter one of them.
Idea: n variables as N points, "X<y" as an edge, then get a graph. of the graph
The nodes are sorted so that each x that corresponds to an edge (x, y) is in front of Y. The so-called topological sort.
DFS does a topological sort, and if there is a forward ring, there is no topological ordering, otherwise the nodes that are finished will be accessed
If it is to the front of the current topology sequence. The specific process reference code.
Reference: Algorithmic Race Primer Classic (second edition) p168~169
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring>using namespace Std;int vis[1100];int topo[1100],g[1100][1100],t,n,m;bool dfs (int u) {vis[u] = -1;//Start Access node for (int v = 0; v < n; v++) {if (G[u][v])//exists side {if (vis[v]<0)//Indicates node V is in Access, (that is, call DFS (U) is still in the stack, not yet returned) Retu RN false; else if (!vis[v])//does not have access to the node Dfs (v);//access to the Node}} vis[u] = 1;//node Access node Topo[--t] = u;//Stores the current node to the topology The first return of the sequence is true;} BOOL Toposort () {t = n; memset (vis,0,sizeof (VIS)); for (int u = 0; u < n; u++) {if (!vis[u]) if (!dfs (U)) return false; } return true; int main () {while (~scanf ("%d%d", &n, &m) && (n| | m)) {memset (g,0,sizeof (G)); while (m--) {int u,v; scanf ("%d%d", &u,&v); G[--U][--V] = 1; } if (Toposort ()) {for (int i = 0; i < n; i++) {if (i!=n-1) printf ("%d", topo[i]+1); else printf ("%d\n", topo[i]+1); }} else printf ("no\n"); } return 0;}
UVA10305 ordering Tasks "DFS" "Topology Sort"