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 from 1 to n) and m are the number of direct Preceden Ce relations between tasks. After this, there'll be m lines with II integers i and J, representing the fact that task i must be executed before task 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
Ideas:
Topological sort naked question, using the letter of the DFS on the purple Book
Implementation code:
#include <bits/stdc++.h>using namespacestd;Const intM = $;intx,y,n,m,vis[m],topo[m],g[m][m],t;BOOLDfsintu) {Vis[u]= -1;//currently in the judgment of the for(inti =1; I <= N;i + +){ if(G[u][i]) {if(Vis[i] <0)return false; if(!vis[i]&&!dfs (i))return false; }} Vis[u]=1; topo[t--] =u; return true;}BOOLToposort () {T=N; memset (Vis,0,sizeof(VIS)); for(inti =1; I <= N;i + +) if(!vis[i]&&!dfs (i))return false; return true;}intMain () { while(cin>>n>>m) { if(n==0&&m==0) Break; Memset (g,0,sizeof(g)); while(m--) {cin>>x>>y; G[x][y]=1; } if(Toposort ()) { for(inti =1; I <= N;i + +){ if(i==n) cout<<topo[i]<<Endl; Elsecout<<topo[i]<<" "; } } } return 0;}
UVa 10305-ordering Tasks (topological sort naked)