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
板子题
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
using namespace std;
#define N 1005
int book[N],map[N][N],a[N];
void topo(int n)
{
int i,j,k;
for(i=1; i<=n; i++)
{
k=1;
while(book[k])
k++;
a[i]=k;
book[k]=-1;
for(j=1; j<=n; j++)
{
if(map[k][j])
book[j]--;
}
}
}
int main ()
{
int m,n;
while(~scanf("%d%d",&n,&m)&&(n+m))
{
memset(map,0,sizeof(map));
memset(book,0,sizeof(book));
memset(a,0,sizeof(a));
int c,b;
while(m--)
{
scanf("%d%d",&c,&b);
if(!map[c][b])
{
map[c][b]=1;
book[b]++;
}
}
topo(n);
printf("%d",a[1]);
for(int i=2; i<=n; i++)
printf(" %d",a[i]);
printf("\n");
}
return 0;
}