Description
![Download as PDF Download as PDF](http://uva.onlinejudge.org/components/com_onlinejudge/images/button_pdf.png)
Problem F
Ordering Tasks
Input: standard input
Output: standard output
Time Limit: 1 second
Memory Limit: 32 MB
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
(The Joint Effort Contest, Problem setter: Rodrigo Malta Schmidt)
#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
int MAP[110][110],c[110],n,m,t;
int topo[110];
bool dfs(int u)
{
c[u]=-1;
for(int v=1; v<=n; v++)
if(MAP[u][v])
{
if(c[v]< 0)
return false;
else if(c[v]==0&&!dfs(v))
return false;
}
c[u]=1;
topo[t--]=u;
return true;
}
bool toposort()
{
t=n;
memset(c,0,sizeof(c));
for(int u=1; u<=n; u++)
if(!c[u])
if(!dfs(u))
return false;
return true;
}
int main()
{
int a,b;
while(scanf("%d%d",&n,&m)!=EOF&&(n+m)!=0)
{
memset(MAP,0,sizeof(MAP));
for(int i=1; i<=m; i++)
{
cin>>a>>b;
MAP[a][b]=1;
}
if(toposort())
{
printf("%d",topo[1]) ;
for(int i=2; i<=n; i++)
printf(" %d",topo[i]);
cout<<endl;
}
}
return 0;
}