John has n tasks to do. Unfortunately, the tasks are not independent and the execution of one task is only possible if other tasks have already been executed.
Input
The input will consist of several instances of the problem. Each instance begins with a line containing two integers, 1 ≤ n ≤ 100 and m. n is the number of tasks (numbered from 1 to n) and m is the number of direct precedence relations between tasks. After this, there will be m lines with two integers i and j, representing the fact that task i must be executed before task j. An instance with n = m = 0 will 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
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 const int maxn=105; 5 using namespace std; 6 int c[maxn],n,m; 7 int topo[maxn],t,G[maxn][maxn]; 8 bool dfs(int u) 9 { 10 c[u]=-1; 11 for(int v=0;v<n;v++) 12 { 13 if(G[u][v])//如果有可行边 14 { 15 if(c[v]<0)return false; 16 else if(!c[v])dfs(v); 17 } 18 } 19 c[u]=1,topo[--t]=u;//记录到数组中 20 return true; 21 } 22 bool toposort() 23 { 24 t=n; 25 memset(c,0,sizeof c); 26 for(int i=0;i<n;i++)//要保证每个数都可行 27 if(!c[i]) 28 if(!dfs(i)) 29 return false; 30 return true; 31 } 32 int main() 33 { 34 while(scanf("%d%d",&n,&m)==2,n) 35 { 36 memset(G,0,sizeof G); 37 for(int i=0;i<m;i++) 38 { 39 int u,v; 40 scanf("%d%d",&u,&v); 41 G[--u][--v]=1; 42 } 43 if(toposort()) 44 { 45 for(int i=0;i<n-1;i++) 46 printf("%d ",topo[i]+1); 47 printf("%d ",topo[n-1]+1); 48 } 49 else 50 printf("No "); 51 } 52 return 0; 53 }