本文已参与「新人创作礼」活动,一起开启掘金创作之路。
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 Output1 4 2 5 3
题意:
每一项任务都有一个编号,输入的两个编号表示只有做过前边的编号任务才能接着去做后边的编号任务,
让我们输出做任务的顺序.
附上ac代码:
ps:我的第一个拓扑题,嘿嘿嘿~
#include<stdio.h>
#include<string.h>
int a[110],b[110],t[110],book[110],s[110];
int main()
{
int n,m;
while(~scanf("%d %d",&n,&m)&&(n+m))
{
memset(t,0,sizeof(t));
memset(s,0,sizeof(s));
memset(book,0,sizeof(book));
for(int i=0; i<m; i++)
{
scanf("%d %d",&a[i],&b[i]);
s[b[i]]++; ///入度加一
}
int k=0;
for(int i=1; i<=n; i++)
{
if(s[i]==0)
{
book[i]=1; ///标记
t[k++]=i; ///入度为零的存进t数组
}
}
for(int i=0; i<n; i++) ///t数组中一个一个判断
{
for(int j=0; j<m; j++) ///m个关系 依次判断
{
if(t[i]==a[j]) ///与a[i]有关系的b[i]入度--
{
s[b[j]]--;
if(s[b[j]]==0)
{
t[k++]=b[j]; ///入度为零 存入t数组
}
}
}
}
for(int i=0; i<n; i++)
if(i<n-1)printf("%d ",t[i]); ///格式
else printf("%d\n",t[i]);
}
return 0;
}