Ordering Tasks(拓扑排序)

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

#include<stdio.h>
#include<string.h>
int f[105][105];
int v[105];
int n,m;
void topo()
{
	int count=0,i,j;
	while(count<n)
	{
		for(i=1;i<=n;i++)
		{
			if(!v[i])
			{
				v[i]=-1;
				printf("%d",i);
			    count++;
			    if(count!=n)
					printf(" ");
				else
					printf("\n");
				for(j=1;j<=n;j++)
				{
				
					if(i!=j&&f[i][j])
					{
						f[i][j]=0;
						v[j]--;
					}
				}
			}
		}
	}
}
int main()
{
	int i;
	
	while(scanf("%d%d",&n,&m))
	{
		if(!m&&!n)
			break;
		memset(f,0,sizeof(f));
		memset(v,0,sizeof(v));
		for(i=0;i<m;i++)
		{
			int a,b;
			scanf("%d%d",&a,&b);
			f[a][b]=1;
			v[b]++;
		}
		topo();
    }
	return 0;
}
    原文作者:拓扑排序
    原文地址: https://blog.csdn.net/u011641865/article/details/38542033
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞